2010-05-29 62 views
5

我試圖建立User - UserProfile關係,顯示窗體並保存數據。Django,ModelForms,用戶和用戶配置文件 - 不哈希密碼

提交時,數據被保存,密碼字段不被散列。

Forms.py

class UserForm(forms.ModelForm): 
    username = forms.RegexField(label="Username", max_length=30, 
     regex=r'^[\[email protected]+-]+$', 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'] 

回答

8

編輯:這個答案寫

後要設置用戶密碼原來的問題是編輯,你不設置profile.user.password = new_password - 這是在這種情況下使用模型表達的是什麼;它會直接將它設置爲非哈希值。

您需要使用適當的API來設置密碼。所以,在profile.save()地說:

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

要殺死help_text,要麼不使用快速form.as_foo渲染器,或覆蓋領域有沒有在你的ModelForm的初始化的help_text()方法(請參閱Django表單文檔)a

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