Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-viewsdjango-forms

Not able to send the comment to db and getting "IntegrityError at /add-comment NOT NULL constraint failed: core_comment.post_id"


models.py

This was the model I created :


class Post(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4)
    user = models.CharField(max_length=100)
    image = models.ImageField(upload_to='post_images')
    caption = models.TextField()
    created_at = models.DateTimeField(default=datetime.now)
    no_of_likes = models.IntegerField(default=0)


    def __str__(self):
        return self.user


class Comment(models.Model):
    post = models.ForeignKey(
        Post, on_delete=models.CASCADE, related_name='comments')
    name = models.CharField(max_length=80)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s - %s' % (self.post.user, self.name)

views.py

I am not able to create object at the backend. would be helpful if anyone knew how to call post and add it to the views.

@login_required(login_url='signin')
def add_comment(request):
    if request.method == 'POST':
        # import pdb
        # pdb.set_trace()
        user = request.user.username
        comment = request.POST['comment']

        new_comment = Comment.objects.create(name=user, body=comment)
        new_comment.save()

        return redirect('/')
    else:
        return redirect('/')

index.html : along with forms

 <!-- Comment section  -->

                        <form action="add-comment" method="POST" enctype="multipart/form-data">
                            {% csrf_token %}
                            <div>
                                <!-- Comment section typing box  -->
                                <div class="bg-gray-100 bg-gray-100 rounded-full rounded-md relative ">
                                    <!-- <a href="/add-comment?post_id={{post.id}}"> -->
                                    <input type="text" placeholder="post a comment"
                                        class="bg-transparent max-h-10 shadow-none" name="comment" id="comment">
                                    <div class="absolute bottom-0 flex h-full items-center right-0 right-3 text-xl space-x-2">
                                        <button class="button bg-blue-700" type="submit">submit</button>
                                    </div>
                                </div>
                        </form>

I am not able to bring the comment to the backend as I am new to django.enter image description here

comment section looks like this

error picture

tracebackcall

enter image description here


Solution

  • You should specify for which post you add the comment, so:

    @login_required(login_url='signin')
    def add_comment(request, pk):
        if request.method == 'POST':
            user = request.user.username
            comment = request.POST['comment']
            new_comment = Comment.objects.create(
                name=request.user.username, body=comment, post_id=pk
            )
            return redirect('/')
        else:
            return redirect('/')

    in the URLs, you thus will need to provide a primary key:

    urlpatterns = [
        path('add-comment/<uuid:pk>/', add_comment, name='add-comment'),
        # …
    ]

    and in the form you will need to pass the primary key of the post:

    <form action="{% url 'add-comment' post.pk %}" method="POST" enctype="multipart/form-data">
        …
    </form>

    where post.pk should be a template expression that resolves to the primary key of the post for which you want to add a comment.


    Note: Please do not store the username of the user, but work with a ForeignKey to the user object. If later the user changes their username, this will result in a lot of trouble. It also makes querying the database less effective, since Django can work with JOINs on ForeignKey fields.