Saving a hashed version of a user password in Django Form does not work

I am trying to save a hashed version of a user password, but it does not work.

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 mine passwordis still saved as plain text. How do I get around this?

+4
source share
2 answers

You need to switch the order of your statements because you named the object with 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 that you also return a response from the method and redirect users accordingly 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})
+6
source

, Django original UserCreationForm 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

, make_password() .

+1

All Articles