问题
I have been trying to save the hashed version of a user password but it's not working.
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()
But my password
still get saved in plain text. How do I come around this?
回答1:
You need to switch the order of your statements, because you have named the object as the same name as the form itself.
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'])
I hope you are also returning a response from the method, and redirecting users appropriately after the POST request.
Consider this version:
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})
回答2:
The best way would be to follow what Django's original UserCreationForm does and override your form's save
method:
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
This way you don't have to make_password()
in every view you use your form.
来源:https://stackoverflow.com/questions/26112779/saving-hashed-version-of-user-password-in-django-form-not-working