Saving Hashed Version of User Password in Django Form Not Working

北城以北 提交于 2019-12-04 08:10:36

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})

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!