uni*_*ack 5 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']
Run Code Online (Sandbox Code Playgroud)
编辑:在写完这个答案后编辑了原始问题
要设置用户的密码,请不要设置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表单文档)a
好的,回答我自己的问题.这对其他人来说可能会派上用场.
将以下内容添加到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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5509 次 |
| 最近记录: |