CoderS
CoderS

Reputation: 153

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

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"),
]

Upvotes: 1

Views: 361

Answers (2)

NixonSparrow
NixonSparrow

Reputation: 6388

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.

Upvotes: -1

sudden_appearance
sudden_appearance

Reputation: 2195

So the initial problem with your question was in this line

user = User.objects.get(username=request.user)

I don't know how it even passed through Django Orm, but it intentionally did return something weird

You don't need to query for user object, because django queries user object to request.user by itself.

Also, django.db.models.Model.objects.filter() always returns QuerySet, which is not a Model object, it's a set of Model objects. When you are querying by primary key and you are sure that there is an instance with this id use

 django.db.Model.objects.get(pk=pk)  # Post.objects.get(id=id) in your case

Note:. this method will reproduce ObjectDoesNotExist exception if there is no object found with this primary key, be aware of that.

Upvotes: 2

Related Questions