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