Django,ModelForms,User和UserProfile - 不是哈希密码

时间:2010-05-29 19:12:54

标签: django django-forms

我正在尝试设置User-UserProfile关系,显示表单并保存数据。

提交后,数据会被保存,除了密码字段不会被哈希处理。

Forms.py

class UserForm(forms.ModelForm):
    username = forms.RegexField(label="Username", max_length=30,
         regex=r'^[\w.@+-]+$', help_text = "My text",
         error_messages = {'invalid':
           "This value may contain only letters, numbers and @/./+/-/_ characters."
         }
    )
    password = forms.CharField(label="Password",
                              widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ["first_name", "last_name", "username",  "email", "password"]

    def clean_username(self):
        username = self.cleaned_data['username']
        if not re.search(r'^\w+$', username):
            raise forms.ValidationError(
                  'Username can contain only alphanumeric characters')
        try:
            User.objects.get(username=username)
        except ObjectDoesNotExist:
            return username
        raise forms.ValidationError('Username is already taken')

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['user_is']

2 个答案:

答案 0 :(得分:8)

编辑:在写完这个答案之后编辑了原始问题

要为用户设置密码,请不要设置profile.user.password = new_password - 在这种情况下使用模型表的操作是什么;这将直接将其设置为未散列的值。

您需要使用适当的API来设置密码。所以,在profile.save()之前:

profile.user.set_password(uform.cleaned_data['password'])

要杀死help_text,要么不使用快速form.as_foo渲染器,要么覆盖该字段,以便在ModelForm的 init ()方法中使用help_text为none(请参阅Django表单文档)一个

答案 1 :(得分:8)

好的,回答我自己的问题。这可能会对其他人派上用场。

将以下内容添加到UserForm

def save(self, commit=True):
   user = super(UserForm, self).save(commit=False)
   user.set_password(self.cleaned_data["password"])
   if commit:
       user.save()
   return user