我一直在尝试保存用户密码的哈希版本,但它无效。
forms.py :
class up_form(forms.ModelForm):
class Meta:
model = Users
fields =['email', 'password', 'username', 'status']
views.py :
from myapp.forms import up_form
from django.contrib.auth.hashers import make_password
def register(request):
if request.method == 'POST':
sign_up = up_form(request.POST or None)
if sign_up.is_valid():
sign_up.password = make_password(sign_up.cleaned_data['password'])
sign_up = sign_up.save(commit = False)
sign_up.status = 1
sign_up.save()
但我的password
仍以纯文本格式保存。我怎么来这个?
答案 0 :(得分:8)
您需要切换语句的顺序,因为您已将对象命名为与表单本身相同的名称。
if request.method == 'POST':
sign_up = up_form(request.POST)
if sign_up.is_valid():
sign_up = sign_up.save(commit = False)
sign_up.password = make_password(sign_up.cleaned_data['password'])
我希望您也从该方法返回响应,并在POST请求后正确地重定向用户。
考虑这个版本:
def register(request):
form = up_form(request.POST or None)
if form.is_valid():
sign_up = form.save(commit=False)
sign_up.password = make_password(form.cleaned_data['password'])
sign_up.status = 1
sign_up.save()
return redirect('/thank-you/')
return render(request, 'sign_up_form.html', {'form': form})
答案 1 :(得分:2)
最好的方法是遵循Django的原始UserCreationForm所做的事情并覆盖表单的errSecParam
方法:
save
这样,您在使用表单的每个视图中都不需要class UpForm(forms.ModelForm):
class Meta:
model = Users
fields =['email', 'password', 'username', 'status']
def save(self, commit=True):
user = super(UpForm, self).save(commit=False)
user.set_password(self.cleaned_data["password"])
if commit:
user.save()
return user
。