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

-1👍

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.

2👍

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.

Leave a comment