Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>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])) </code></pre> <p>The author is trying to assign a default value to the author field if one isn't passed in.</p> <p>You could probably shorten the code quite a bit by making a mutable copy of the <code>POST</code> <code>QueryDict</code> to solve the same problem.</p> <p>Does this make more sense to you?</p> <pre><code>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])) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload