Django使用self访问属性

时间:2013-11-24 18:54:34

标签: python django

我在Django中定义了以下表单,我不知道为什么我无法从“save”方法中访问属性“username”:

class ExtendedUserForm(Form):

    required_css_class = 'required'

    username = forms.RegexField(regex=r'^[\w.@+-]+$', ...)

    def save(self, commit = False):

        User.objects.create_user(username = self.username, 
                                    email = self.email, 
                                    password = self.password1)

...每当我尝试访问它时,我都会遇到以下异常:

Exception Type: AttributeError
Exception Value: 'ExtendedUserForm' object has no attribute 'username'

我是Python的新手,尽管已经阅读了官方教程,但我并不完全理解Python类。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

已清理的表单数据位于self.cleaned_data字典下。考虑usernameemailpassword1ExtendedUserForm的字段,您可以像这样写save

def save(self, commit = False):
    User.objects.create_user(username = self.cleaned_data['username'], 
                                email = self.cleaned_data['email'], 
                                password = self.cleaned_data['password1'])

    return super(ExtendedUserForm, self).save(self, commit = commit)