创建Django注释表单时出现ValueError

时间:2019-03-19 12:31:08

标签: python django

使用django创建评论表单时遇到问题。在写完view.py,models.py和html之后,我得到了一个ValueError,上面写着:

Cannot assign "<class 'blog.models.post'>": "Comment.post" must be a "post" instance". 

下面是我的代码。

HTML

{% block content %}
<h1>Add New Comment:</h1>
<form method='POST' action=''>
    {% csrf_token %}
    {{ form.as_p }}
<button type='submit'>Submit</button>
</form>
{% endblock %}

views.py

def add_comment(request, slug):
    po = get_object_or_404(post, slug=slug)
    if request.method == 'POST':
        form = CommentForm(request.POST or None)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('blog:post', slug=post.slug)
    else:
        form = CommentForm()
    return render(request, 'blog/post/add_comment.html', {'form': form})

models.py

class Comment(models.Model):
    post = models.ForeignKey(post, related_name='comments', on_delete=models.CASCADE)
    user = models.CharField(max_length=250)
    email = models.EmailField() 
    body = models.TextField() 
    created = models.DateTimeField(auto_now_add=True) 
    approved = models.BooleanField(default=False) 

    def approved(self):
        self.approved = True
        self.save()

    def __str__(self):
        return self.user

2 个答案:

答案 0 :(得分:1)

您从数据库中获取的帖子为po

po = get_object_or_404(post, slug=slug)

因此,您应该设置form.post = po

def add_comment(request, slug):
    po = get_object_or_404(post, slug=slug)
    if request.method == 'POST':
        form = CommentForm(request.POST or None)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = po
            comment.save()

请注意,通常在Django中,您将对模型使用Post,对从数据库中获取的实例使用post

答案 1 :(得分:0)

尝试一下:

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)