我是django的新手。我正在阅读博客tutorial。从博客教程我无法理解以下部分。任何人都可以解释一下吗?我将非常感激。感谢
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]))
答案 0 :(得分:3)
class CommentForm(ModelForm):
class Meta:
model = Comment
exclude = ["post"]
def add_comment(request, pk):
"""Add a new comment."""
p = request.POST
# if POST has key "body" and p["body"] evalutes to True
if p.has_key("body") and p["body"]: #
author = "Anonymous"
# if the value for key "author" in p evaluates to True
# assign its value to the author variable.
if p["author"]: author = p["author"]
# create comment pointing to Post id: pk passed into this function
comment = Comment(post=Post.objects.get(pk=pk))
# generate modelform to edit comment created above
cf = CommentForm(p, instance=comment)
cf.fields["author"].required = False
# use commit=False to return an unsaved comment instance
# presumably to add in the author when one hasn't been specified.
comment = cf.save(commit=False)
comment.author = author
comment.save()
return HttpResponseRedirect(reverse("dbe.blog.views.post", args=[pk]))
作者正在尝试为作者字段分配默认值(如果未传入)。
你可以通过制作POST
QueryDict
的可变副本来解决同样的问题,从而缩短代码。
这对你更有意义吗?
class CommentForm(ModelForm):
class Meta:
model = Comment
exclude = ["post"]
def add_comment(request, pk):
"""Add a new comment."""
p = request.POST.copy()
if p.has_key("body") and p["body"]:
if not p["author"]:
p["author"] = 'Anonymous'
comment = Comment(post=Post.objects.get(pk=pk))
cf = CommentForm(p, instance=comment)
cf.save()
return HttpResponseRedirect(reverse("dbe.blog.views.post", args=[pk]))
答案 1 :(得分:0)
它检查使用表单评论的用户是否填写了表单(作者和正文) 如果用户没有输入作者姓名,则会将其设置为匿名,如果两个字段(作者和正文)都为空,则会重定向回到表单..