gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 09:53:28 25 4
gpt4 key购买 nike

View .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/通过管理面板添加评论,但如果我尝试通过表单动态添加评论,则不会保存评论。
我只在模板中添加了表单。

最佳答案

您已定义字段 body在您的 CommentForm .它在您的表单中是必需的,因为您没有包含 blank=True您模型中该字段的参数。这意味着当您 POST 请求并检查表单是否有效时 form.is_valid() ,表单需要一个名称为 body 的元素在请求中。如果它不存在,则不会验证并且不会保存内容。

进行以下更改:

  • 将您的 View 更改为
    ...
    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()
    ...
  • 将您的 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>
    ...
  • 关于python - 无法在 Django 中使用 ModelForm 向帖子添加评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61973997/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com