无法在Django中使用ModelForm在帖子中添加评论

views.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)

models.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}'

表格

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

如果我使用外壳程序/通过管理面板添加评论,但是如果我尝试通过表单动态添加评论,则不会保存该评论,也不会显示任何错误。 我仅在模板中添加了表单。

评论
iid
iid

You have defined field body in your CommentForm. It's required in your form, because you didn't include blank=True argument in your model for this field. This means that when you POST request and check if form is valid with form.is_valid(), the form expects an element with a name body in the request. If it's not there, it will not validate and content won't be saved.

进行以下更改:

  1. Change your view to

    ...
    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. Change your HTML to this:

    ...
    <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>
    ...
    
点赞
评论
小自摸
小自摸

在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 %}

这对我有用。

点赞
评论