【发布时间】:2020-09-09 03:04:15
【问题描述】:
我正在使用 Django 中的模态和表单我为我的帖子模态创建了一个评论模式我使用外键将我的评论与帖子相关联,通过手动将评论添加到我网页的管理部分的帖子中,一切正常,但是一旦我尝试使用我的表单的前端表示来做同样的事情,以便用户可以向帖子添加评论,它不会按预期工作,而且我也无法自动将我的帖子与我的评论相关联,我现在已经改变了 2 天的东西,结果仍然是一样的。谁能帮我 :{ 这就是我的模式的样子:
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 中没有实例,您正在使用
forms.CreateArticle -
idk 我应该改变什么帮助我回答如果你离开它会起作用
-
是的,它改变了行 ``` form = forms.CreateArticle(request.POST, request.FILES) ``` to ``` form = forms.CommentForm(request.POST, request.FILES )```
-
你确定这是编译的代码吗?
-
是的,顺便说一句,它没有显示任何错误
标签: python html django django-models