在Django DetailView中发表评论

时间:2020-10-06 12:15:42

标签: django django-models

我需要在“帖子详细视图”中添加评论。我可以提交评论表单,但它不会保存评论,而是当我单击“提交”按钮时,页面会重新加载,评论也不会保存。

在models.py

class Comment(models.Model):
post=models.ForeignKey(Post,on_delete=models.CASCADE,related_name="comments")
name=models.CharField(max_length=200)
comment=models.TextField()
created_date=models.DateTimeField(default=timezone.now)
approved_comment=models.BooleanField(default=False)

def __str__(self):
    return self.comment

在forms.py中:

from django import forms
from .models import Comment

class CommentForm(forms.ModelForm):
    class Meta:
        model=Comment
        fields=['name','comment']

在views.py中:

from django.views.generic.edit import ModelFormMixin
from .forms import CommentForm

class PostDetailView(ModelFormMixin,DetailView):
    model=Post
    form_class=CommentForm

    def get_context_data(self,*args,**kwargs):
        context=super().get_context_data(**kwargs)
        context['form']=self.get_form()
        return context
    def post(self,request,*args,**kwargs):
        self.object=self.get_object()
        form=self.get_form()
        if form.is_valid():
           return self.form_valid(form)
        else:
           return self.form_invalid(form)
    def form_valid(self,form):
        form.instance.post=self.object
        form.save()
        return super().form_valid(form)

0 个答案:

没有答案