为什么Django即使数据有效也不接受表单中的数据?Django python
我在Django中使用Modals和Forms我为我的帖子模式创建了一个评论模式我使用ForeignKey将我的评论与帖子关联起来,通过手动将评论添加到我网页管理部分的帖子中,效果很好,但是,当我尝试使用我的表单的前端表示来做同样的事情,以便用户可以向帖子添加评论时,它并没有按照预期工作,而且我也无法自动将我的帖子与我的评论关联起来,我已经更改表单两天了,结果仍然是一样的。有人能帮我吗{ 这就是我的模态的样子:为什么Django即使数据有效也不接受表单中的数据?Django python,python,html,django,django-models,Python,Html,Django,Django Models,我在Django中使用Modals和Forms我为我的帖子模式创建了一个评论模式我使用ForeignKey将我的评论与帖子关联起来,通过手动将评论添加到我网页管理部分的帖子中,效果很好,但是,当我尝试使用我的表单的前端表示来做同样的事情,以便用户可以向帖子添加评论时,它并没有按照预期工作,而且我也无法自动将我的帖子与我的评论关联起来,我已经更改表单两天了,结果仍然是一样的。有人能帮我吗{ 这就是我的模态的样子: class Comment(models.Model): post = mo
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>
{{comment_form}}
{%csrf_令牌%}
提交
正确的代码应该如下所示
def文章详细信息(请求,slug):
articles=Article.objects.all()
注释形式=注释形式()
post=获取对象或404(文章,slug=slug)
comments=post.comments.filter(active=True)
如果request.method==“POST”:
表单=注释表单(数据=request.POST,文件=request.files)
如果form.is_有效():
#创建注释对象,但不保存到数据库syet
new_comment=form.save(commit=False)
new_comment.post=post
新建_comment.save()
其他:
注释形式=注释形式()
返回呈现(请求'articles/article\u detail.html',{'article':post,'articles':articles,'comment\u form':comment\u form})
comment\u表单中没有实例,您正在使用forms.CreateArticle
idk我应该更改什么帮助我plz答案如果您离开它会起作用是的,将它更改为行``form=forms.CreateArticle(request.POST,request.FILES)``到``form=forms.CommentForm(request.POST,request.FILES)```你确定这是代码编译吗?是的,顺便说一下,它没有显示任何错误