Django 2.2 Python 3.6 填写表格后,评论到达django,但没有存储在数据库中......在同一个应用程序中发布和评论模型。我没有任何追溯。我不明白我忽略了什么和在哪里......
视图.py
def post_detail(request, slug):
post = Post.objects.get(slug=slug)
if request.method == 'POST':
new_comment_form = NewCommentForm(request.POST, instance=post)
if 'add_comment' in request.POST and new_comment_form.is_valid():
comment = new_comment_form.save(commit=False)
comment.post = post
comment.author = request.user
comment.content = request.POST.get('content')
comment.active = True
comment.save()
else:
new_comment_form = NewCommentForm()
context = {
'post': post,
'new_comment_form': new_comment_form,
}
template = 'content/post_detail.html'
return render(request, template, context)
表格.py
class NewCommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = (
'content',
)
def save(self, commit=True):
comment = super(NewCommentForm, self).save(commit=False)
comment.content = self.cleaned_data['content']
if commit:
comment.save()
return comment
模型.py
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='post_comments', on_delete=models.CASCADE, verbose_name='Комментарии')
author = models.ForeignKey(VertexUser, related_name='comment_author', on_delete=models.CASCADE, verbose_name='Автор')
content = models.TextField('Содержание', blank=True)
like = models.PositiveIntegerField('Лайки', default=0, blank=True, null=True)
dislike = models.PositiveIntegerField('Дизлайки', default=0, blank=True, null=True)
publication_date = models.DateTimeField('Дата публикации', auto_now=True, null=True)
active = models.BooleanField('Опубликовано', default=True)
def __str__(self):
return f'Автор {self.author} | Опубликовано {self.publication_date}'
class Meta:
verbose_name = 'Комментарий'
verbose_name_plural = 'Комментарии'
感谢您的关注。
帖子中的绑定是多余的。