Django表单占位符request.user

时间:2013-09-02 18:58:09

标签: django forms

我的观点:

form1 = UserProfile(request.POST or None, user=request.user)

我的表格:

class UserProfile(forms.Form):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop("user")
        super(UserProfile, self).__init__(*args, **kwargs)

    first_name = forms.CharField(max_length=30,required=True,widget=forms.TextInput(attrs={'placeholder': self.user.first_name }))
    last_name = forms.CharField(max_length=30,required=True,widget=forms.TextInput(attrs={'placeholder': self.user.last_name }))
  

/ settings /的NameError   名称'self'未定义   请求方法:GET   请求网址:

http://localhost:8000/settings/
  

Django版本:1.5.2异常类型:NameError异常值:name   “自我”未定义

到目前为止,我试图找到解决方案,到目前为止,我想出了这些代码,然后仍然出错。

1 个答案:

答案 0 :(得分:0)

您不能在表单字段定义中使用self,因为self变量仅在方法中可用。

您的字段是动态的,取决于构造函数中传递的user变量。在__init__.py self.user中定义您的动态字段:class UserProfile(forms.Form): def __init__(self, *args, **kwargs): self.user = kwargs.pop("user") super(UserProfile, self).__init__(*args, **kwargs) self.fields['first_name'] = forms.CharField(max_length=30,required=True,widget=forms.TextInput(attrs={'placeholder': self.user.first_name })) self.fields['last_name'] = forms.CharField(max_length=30,required=True,widget=forms.TextInput(attrs={'placeholder': self.user.last_name }))

{{1}}

另见: