无法在Django中使用ModelForm向帖子添加注释

2024-06-26 13:57:43 发布

您现在位置:Python中文网/ 问答频道 /正文

视图.py

def postdetail(request,pk): # Single Post view.

    post = Post.objects.get(id=pk)
    comment = post.comments.all()
    comment_count = comment.count()

    if request.user.is_authenticated:

        if request.method == 'POST':
            form = CommentForm(data=request.POST)
            content = request.POST['cMessage']

            if form.is_valid():
                print("Yes valid")
                form.instance.body = content
                new_comment = form.save(commit=False)
                print(new_comment)
                new_comment.post = post
                new_comment.user = request.user
                new_comment.save()
                return redirect('blog-home')
        else:

            form = CommentForm()

    context = {
        'comment_form': CommentForm,
        'post' : post,
        'comments': comment,
        'count': comment_count,
    }

    return render(request,'post/postdetail.html', context=context)

型号.py

class Comment(models.Model):

    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='comments')
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    # active = models.BooleanField(default=True)

    class Meta:
        ordering = ('created',)

    def __str__(self):
        return f'Comment by {self.user} on {self.post}'

forms.py

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['body']

模板

{% if request.user.is_authenticated %}
    <!-- respond -->
    <div class="respond">
        <h3>Leave a Comment</h3>
            <!-- form -->
                <form name="contactForm" id="contactForm" method="post" action="">
                {% csrf_token %}
                <fieldset>

                    <div class="message group">
                        <label  for="cMessage">Message <span class="required">*</span></label>
                        <textarea name="cMessage"  id="cMessage" rows="10" cols="50" ></textarea>
                    </div>

                    <button type="submit" class="submit">Submit</button>

                </fieldset>
                </form> <!-- Form End -->
    </div> 
{% endif %}

如果我使用shell/through管理面板添加注释,也不会显示错误,但是如果我尝试通过表单动态添加注释,则不会保存注释。 我只在模板中添加了表单


Tags: nameformnewifmodelsrequestcountcomment
2条回答

In views.py

def postdetail(request):
    print(Comment.objects.all())

    if request.method == 'POST':
            form = CommentForm(data=request.POST)
            content = request.POST['body']

            if form.is_valid():
                print("Yes valid")
                new_comment = form.save(commit=False)
                print(new_comment)
                new_comment.post = post
                new_comment.user = request.user
                new_comment.save()
                return redirect('blog-home')
        else:
            form = CommentForm()
    return render(request,'temp/postdetail.html', context=context)

在html文件中

{% if request.user.is_authenticated %}
    <div class="respond">
        <h3>Leave a Comment</h3>
        <form name="contactForm" id="contactForm" method="post" action="">
            {% csrf_token %}
            <textarea name="body"cols="30" rows="10"></textarea>
            <button type="submit" class="submit">Submit</button>
        </form>
    </div>
{% endif %}

这对我有用

您已经在CommentForm中定义了字段body。它在表单中是必需的,因为您没有在模型中为此字段包含blank=True参数。这意味着,当您发布请求并检查表单是否对form.is_valid()有效时,表单希望请求中有一个名为body的元素。如果它不在那里,它将不会验证,也不会保存内容

进行以下更改:

  1. 将您的视图更改为

    ...
    if request.method == 'POST':
        form = CommentForm(data=request.POST)
        if form.is_valid():
            new_comment = form.save(commit=False)
            new_comment.post = post
            new_comment.user = request.user
            new_comment.save()
            return redirect('blog-home')
        else:
            print(form.errors) # or log it to a file, if you have logging set up
    
    form = CommentForm()
    ...
    
  2. 将您的HTML更改为:

    ...
    <form name="contactForm" id="contactForm" method="post" action="">
        {% csrf_token %}
        <fieldset>
            <div class="message group">
                <label  for="body">Message <span class="required">*</span></label>
                <textarea name="body" id="cMessage" rows="10" cols="50" ></textarea>
                {{ comment_form.body.errors }}
            </div>
            <button type="submit" class="submit">Submit</button>
        </fieldset>
    </form>
    ...
    

相关问题 更多 >