2011-09-21 83 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