为什么不是django找到我的“正确”命名的模板文件夹?

时间:2015-04-21 17:44:29

标签: python django modelform

this tutorial中,有一个ModelForm

from django.forms import ModelForm

class CommentForm(ModelForm):
    class Meta:
        model = Comment
        exclude = ["post"]

def add_comment(request, pk):
    """Add a new comment."""
    p = request.POST

    if p.has_key("body") and p["body"]:
        author = "Anonymous"
        if p["author"]: 
            author = p["author"]

        comment = Comment(post=Post.objects.get(pk=pk))
        cf = CommentForm(p, instance=comment)
        cf.fields["author"].required = False

        comment = cf.save(commit=False)
        comment.author = author
        comment.save()
    return HttpResponseRedirect(reverse("dbe.blog.views.post", args=[pk]))

他们从哪里获得评论comment = Comment(post=Post.objects.get(pk=pk))?如果我们还没有制作或保存它,那么如何才能通过评论,并且该功能的整个目的是“add_comment”?如果它已经存在,我不明白为什么我们会再次添加它。感谢

1 个答案:

答案 0 :(得分:2)

这一行没有从db获得评论,它是creating一个新的评论实例。

comment = Comment(post=Post.objects.get(pk=pk))

如果我们更详细地重写它可能会更容易理解:

post = Post.objects.get(pk=pk) # fetch the post based on the primary key
comment = Comment(post=post) # create a new comment (it is not saved at this point)
...
comment.save() # the comment is saved to the db