[SOLVED] Django comment form not submitting data [ERROR: function' object has no attribute 'objects]

Issue

I have a comment form on a post page for submitting user comment. I keep getting this error:

'function' object has no attribute 'objects'

The full trace-back:

Traceback (most recent call last):
File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\env\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\Users\Steve Njuguna\Desktop\MoringaCore\Django-Instagram-Clone\App\views.py", line 208, in AddComment
    comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id)

Exception Type: AttributeError at /post/1/comment
Exception Value: 'function' object has no attribute 'objects'

Most answers on SO refer to identical model & function names but that is not my case. This is my model:

class Comment(models.Model):
    opinion = models.CharField(max_length=2200, verbose_name='Comment', null=False)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

    def __str__(self):
        return self.comment

    class Meta:
        verbose_name_plural = 'Comments'

My view

@login_required(login_url='Login')
def AddComment(request, id):
    post = Post.objects.filter(id=id)
    user = User.objects.get(username=request.user)
    if request.method == "POST":
        usercomment = request.POST['comment']
        comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id)
        comment_obj.save()
        messages.success(request, '✅ Your Comment Was Created Successfully!')
        return redirect('Home')
    else:
        messages.error(request, "⚠️ Your Comment Wasn't Created!")
        return redirect('Home')

And my form:

<form method="POST" action="{% url 'AddComment' post.id %}">
   {% csrf_token %}
   <div class="d-flex flex-row add-comment-section mt-4 mb-4">
      <img class="img-fluid img-responsive rounded-circle mr-2" src="{{ user.profile.profile_image.url }}" width="38">
      <textarea class="form-control mr-3" rows="1" name="comment" placeholder="Your Comment" required></textarea>
      <button class="btn btn-primary btn-lg" type="submit">Comment</button>
   </div>
</form>

And lastly my URL:

urlpatterns = [
    path('post/<int:id>/comment', views.AddComment, name="AddComment"),
]

Solution

Delete user = User.objects.get(username=request.user) from your view, then change this:

comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id)

to this:

comment_obj = Comment.objects.create(opinion=usercomment, author=request.user, post=post)

Because you should not pass id where objects are seeked (in ForeignKey we need specific object, not its id).

Also change this:

post = Post.objects.filter(id=id)

To this:

post = Post.objects.get(id=id)

Because you need specific object, not whole QuerySet of them.

Answered By – NixonSparrow

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *