简体   繁体   English

创建 Django 评论表单时出现 ValueError

[英]ValueError when creating Django comment form

I have a problem when I was creating the comment form with django.我在使用 django 创建评论表单时遇到问题。 After I wrote my view.py, models.py and html, I got an ValueError that said:在我写完 view.py、models.py 和 html 之后,我得到了一个ValueError ,它说:

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

Below are my codes.下面是我的代码。

HTML 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视图.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模型.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

The post you fetched from the database is po :您从数据库中获取的帖子是po

po = get_object_or_404(post, slug=slug)

Therefore you should set form.post = po :因此你应该设置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()

Note that normally in Django you would use Post for your model and post for the instance you fetch from the database.请注意,通常在 Django 中,您会将Post用于您的模型,并为您从数据库中获取的实例使用post

Try it:尝试一下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM