为什么Django不接受表单中的数据——即使数据是有效的?Django python



我在Django中使用模式和表单。我为我的帖子模式创建了一个评论模式。我使用ForeignKey将我的评论与帖子关联起来。通过从我的网页的管理部分手动向帖子添加评论,一切都很好。但一旦我尝试使用我的表单的前端复制来做同样的事情,这样用户就可以向帖子添加注释,它没有按预期工作,我也无法自动将我的帖子与我的评论联系起来,我已经更改了两天的内容,结果仍然是一样的。有人能帮我吗:{这就是我的模式:

class Comment(models.Model):
post = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=200)
text =  RichTextField()
created_date = models.DateTimeField(auto_now_add= True)
active = models.BooleanField(default=False)

形式:

class CommentForm(forms.ModelForm):
class Meta:
model = models.Comment
fields = ['author', 'text']


这是我在Views.py:


def article_detail(request, slug):
article = Article.objects.get(slug = slug)
articles = Article.objects.all()
comment_form = CommentForm()

post = get_object_or_404(Article, slug=slug)
comments = post.comments.filter(active=True)

if request.method == 'POST':
form =  forms.CreateArticle(request.POST, request.FILES)
if form.is_valid():
# Create Comment object but don't save to database syet
new_comment = form.save()
# Assign the current post to the comment
new_comment.post =  comment_form.instance.article_id
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
return render(request, 'articles/article_detail.html', {'article':article, 'articles':articles, 'comment_form': comment_form , })

并且表单前端表示为:


<form method="post" style="margin-top: 1.3em;">
{{ comment_form }}
{% csrf_token %}
<button type="submit" class="btn btn-outline-success">Submit</button>
</form>

您的正确代码应该看起来像这个

def article_detail(request, slug):
articles = Article.objects.all()
comment_form = CommentForm()

post = get_object_or_404(Article, slug=slug)
comments = post.comments.filter(active=True)

if request.method == 'POST':
form =  CommentForm(data=request.POST, files=request.FILES)
if form.is_valid():
# Create Comment object but don't save to database syet
new_comment = form.save(commit=False)
new_comment.post = post
new_comment.save()
else:
comment_form = CommentForm()
return render(request, 'articles/article_detail.html', {'article':post, 'articles':articles, 'comment_form': comment_form })

最新更新