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]))
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
POSTQueryDictto solve the same problem.Does this make more sense to you?