2013-04-26 31 views
1

我有一個應用程序可以讓用戶創建博客並允許其他用戶對每個其他博客發表評論。問題是。爲了創建評論對象,我需要博客ID和文本。我可以通過帖子獲取文本數據,但我無法從POST獲取博客ID,但我可以想到的唯一方法是通過值字段的形式Django從POST開始抓取值域

如何從POST中獲取值字段?

我的模型

class Blog(models.Model): 

    user = models.ForeignKey(User) 
    name = models.CharField(max_length=100) 
    created = models.DateTimeField(auto_now_add=True) 
    description = models.TextField() 



class BlogComment(models.Model): 
    created = models.DateTimeField(auto_now_add=True) 
    user = models.ForeignKey(User) 
    body = models.TextField() 
    blog = models.ForeignKey(Blog) 

我forms.py

class BlogCommentForm(forms.ModelForm): 
     text = forms.CharField(required=False) 
     class Meta: 
       model = BlogComment 
       fields =() 



<form method ="POST"> {% csrf_token %} 

    <input type = "hidden" name="d" value= "blog.id" /> 

{{form}} 
</form> 

我的觀點

def Blogs(request,blog_id): 
     form = BlogCommentForm(request.POST) 

     if request.method == "POST": 
      if form.is_valid(): 

       text = form.cleaned_data['text'] 
       value = form.cleaned_data['value'] 

     form = BlogCommentForm() 
     blog.objects.get(pk=blog_id) 

    comment = BlogComment.objects.filter(blog=blog) 

return render(request,'blogcomment.html',{'comment':comment,'form':form}) 
+0

你需要一些大括號,那裏有'value =「{{blog.id}}」' – 2013-04-26 16:24:19

回答

1
request.POST['d'] 

或避免引發Exception如果它不存在使用

request.POST.get('d', False) 
+0

request.POST就像是一個python字典,你可以使用名字獲得值。 – 2013-04-26 16:32:02

+0

另外,請參閱我對模板中丟失的大括號的評論。 – 2013-04-26 16:34:07

+0

int()與基數10的無效文字:'第五'我得到這個錯誤。我該怎麼辦? – donkeyboy72 2013-04-26 16:56:31

1

您可以隨時從url中的?=參數獲取博客ID。 當用戶去評論某人的博客時,url可能是http://yoursite.com/blog/id/commenthttp://yoursite.com/blog/comment?blogid=12345

+0

好的,我如何獲取URL? – donkeyboy72 2013-04-26 17:02:53

+0

你可以使用request.path獲取網址,但爲什麼這麼複雜讓你自己使用django的評論,並在django評論中爲你的博客創建一個參考 – dusual 2013-04-26 17:54:28

+0

@dusual好吧,我已經提出了評論功能,很簡單,但我只是不知道如何獲得id。你可以給我一個關於如何使用request.path獲取url的例子嗎?進入我的觀點 – donkeyboy72 2013-04-27 09:27:44