为什么Django找不到我的“正确”命名的templates文件夹?

2024-04-27 00:02:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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]))

他们从哪里得到评论?如果我们还没有制作或保存一条注释,而该功能的全部目的是“添加注释”,那么怎么可能已经有了注释呢?如果它已经存在,我不明白我们为什么要再次添加它。谢谢


Tags: falseifrequestsavecommentbodythispost
1条回答
网友
1楼 · 发布于 2024-04-27 00:02:30

此行没有从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

相关问题 更多 >