博客五部曲之二 - 高级博客


573 浏览 2 years, 11 months

15 创建评论

版权声明: 转载请注明出处 http://www.codingsoho.com/

前面讲了如何去显示评论,接下来会讲解如何创建评论

首先创建一个属性获取内容类型

class Post(models.Model):
    @property
    def get_content_type(self):
        instance = self
        content_type = ContentType.objects.get_for_model(instance.__class__)
        return content_type

创建表单CommentForm,content_type和object_id不允许用户输入,设为HiddenInput。

class CommentForm(forms.Form):
    content_type = forms.CharField(widget=forms.HiddenInput)
    object_id = forms.CharField(widget=forms.HiddenInput)
    content = forms.CharField(label="", widget=forms.Textarea)

在view里面将这个form传递给模板,form里隐藏的两个字段直接在初始化数据里赋值,根据当前实例获取。
表单提交之后,根据content_type,object_id记忆当前的内容即可创建新的评论

def post_detail(request, slug=None):
    #
    initial_data = {
        "content_type": instance.get_content_type,
        "object_id":instance.id,
    }
    comment_form = CommentForm(request.POST or None, initial=initial_data)
    if comment_form.is_valid():
        c_type = comment_form.cleaned_data.get("content_type")
        content_type = ContentType.objects.get(model=c_type)
        obj_id = comment_form.cleaned_data.get('object_id')
        content_data = comment_form.cleaned_data.get('content')
        new_content, created = Comment.objects.get_or_create(
            user=request.user,
            content_type=content_type,
            object_id=obj_id,
            content=content_data)
    context = {
        "title" : instance.title,
        "instance" : instance,
        "share_string":share_string,
        "comments":comments,
        "comment_form":comment_form,
    }

模板也稍作修改,添加表单渲染代码

<form method="post" action="">{% csrf_token %}
    {{comment_form|crispy}}
    <input type="submit" value="Post Comments" class="btn btn-default">
</form>