2011-06-21 40 views
-1

我是django的新手。我正在閱讀博客tutorial。從博客教程我無法理解以下部分。任何人都可以解釋我嗎?我將非常感激。感謝任何人都可以解釋我的django博客代碼(詳細內部)

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

有沒有你不明白或想了解更多的特定部分? – TomHarrigan

+0

@TomHarrigan'如果p.has_key(「body」)和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) 。我無法理解這一點。 –

回答

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

筆者試圖如果不通過指定一個默認值作者字段。

你也許可以通過使一個可變的副本縮短代碼頗有幾分POSTQueryDict解決同樣的問題。

這對你更有意義嗎?

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

「如果」author「在POST中,將var作者分配給發佈的任何內容」不正確。 –

+0

感謝您的幫助。 –

+0

@Ignacio - 好點!更像是如果關鍵作者的價值評估爲真? –

0

它檢查誰在使用形式評論的用戶填寫表單(作者和機構) 如果用戶沒有輸入作者姓名,將其設置爲匿名,且如果兩個字段(作者和正文)是空的,它將重定向回形式。

相關問題