I'm new to django. I'm reading blog tutorial.From blog tutorial I'm unable to understand following part. Can any开发者_如何学运维 one explain me? I shall be very thankful. thanks
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]))
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]))
The author is trying to assign a default value to the author field if one isn't passed in.
You could probably shorten the code quite a bit by making a mutable copy of the POST
QueryDict
to solve the same problem.
Does this make more sense to you?
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]))
It checks if the user who is commenting using the form has filled the form ( author and body ) if the user has not entered the author name it will set it as Anonymous , and if both the fields (author and body) are empty, it will redirect back to the form ..
精彩评论