2011-09-21 67 views
0

我定義在forms.py自定義註釋形式休耕Django的意見框架,設置默認表單值

 
class CommentFormWithReply(CommentForm): 
    reply_to = forms.ModelChoiceField(queryset=CommentWithReply.objects.all(), 
      widget=forms.HiddenInput(), required=False) 

    def get_comment_model(self): 
     # Use our custom comment model instead of the built-in one. 
     return CommentWithReply 

    def get_comment_create_data(self): 
     # Use the data of the superclass, and add in the title field 
     data = super(CommentFormWithReply, self).get_comment_create_data() 
     return data 

我應該怎麼做才能使這種形式與當前用戶的信息爲默認值(姓名,電子郵件, 網頁 )。

回答

0

可能是這樣的:

https://docs.djangoproject.com/en/dev/ref/forms/fields/#initial

if request.method == 'POST': 
    form = CommentFormWithReply(request.POST) 
    ......................................... 


if request.method == 'GET': 
    default_data = {'name': 'Alexey', 'email': '[email protected]', 'webpage': 'http://example.com'} 
    form = CommentFormWithReply(default_data) 
+0

我需要這樣做,我第一次呈現的形式,我想從身份驗證的用戶 – Yasel

+0

使用的數據,如果request.method == 'GET': default_data = {'name':request.user.first_name,'e​​mail':request.user.email,'webpage':your.custom_field.from.userprofile} form = CommentFormWithReply(default_data) – Alexey

+0

or you可以在CommentFormWithReply中完成 – Alexey