Django 评论表单未提交数据 [错误:函数对象没有属性"对象]



我在发布页面上有一个用于提交用户评论的评论表单。我一直收到这个错误:

'function' object has no attribute 'objects'

完整的追溯:

Traceback (most recent call last):
File "C:UsersSteve NjugunaDesktopMoringaCoreDjango-Instagram-Cloneenvlibsite-packagesdjangocorehandlersexception.py", line 47, in inner
response = get_response(request)
File "C:UsersSteve NjugunaDesktopMoringaCoreDjango-Instagram-Cloneenvlibsite-packagesdjangocorehandlersbase.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:UsersSteve NjugunaDesktopMoringaCoreDjango-Instagram-Cloneenvlibsite-packagesdjangocontribauthdecorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:UsersSteve NjugunaDesktopMoringaCoreDjango-Instagram-CloneAppviews.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'

SO上的大多数答案都指向相同的模型&函数名,但我的情况并非如此。这是我的型号:

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'

我的视图

@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')

我的表格:

<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>

最后是我的网址:

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

所以你的问题最初的问题在这一行

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

我甚至不知道它是如何通过Django Orm的,但它故意返回了一些奇怪的

您不需要查询用户对象,因为django自己将用户对象查询到request.user

此外,django.db.models.Model.objects.filter()总是返回QuerySet,它不是Model对象,而是一组Model对象。当您通过主键进行查询,并且您确信有一个具有此id的实例时,请使用

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

注意:。如果找不到此主键的对象,此方法将重现ObjectDoesNotExist异常,请注意。

从视图中删除user = User.objects.get(username=request.user),然后更改为:

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

到此:

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

因为您不应该在查找对象的地方传递id(在ForeignKey中,我们需要特定的对象,而不是它的id(。

同时更改此项:

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

对此:

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

因为您需要特定的对象,而不是它们的全部QuerySet

最新更新