使用make_nupassword djang创建密码用户注册

2024-09-30 01:23:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个注册表单,用户在其中输入用户名/密码组合。在

我希望密码使用MyPBKDF2进行密码哈希。在

我有hashers.py

from django.contrib.auth.hashers import PBKDF2PasswordHasher

    class MyPBKDF2PasswordHasher(PBKDF2PasswordHasher):
        """
        A subclass of PBKDF2PasswordHasher that uses 100 times more iterations.
        """
        iterations = PBKDF2PasswordHasher.iterations * 100

设置.py

^{pr2}$

视图.py

def Registration(request):
    RegForm = RegistrationForm(request.POST or None)
    if request.method == 'POST':
        if RegForm.is_valid():

            clearUserName = RegForm.cleaned_data['userNm']   #set clean username
            hashpass = make_password(RegForm.cleaned_data['userPass'], None, 'pbkdf2_sha256')

            RegForm.save()
            try:
                return HttpResponseRedirect('/Newuser/?userNm=' + clearUserName)
            except:
                raise ValidationError(('Invalid request'), code='300')    ## [ TODO ]: add a custom error page here.
    else:
        RegForm = RegistrationForm()

        return render(request, 'Myapp/reuse/register.html', {
            'RegForm': RegForm 
        })

表单.py c

lass RegistrationForm(ModelForm):
    userPass = forms.CharField(widget=forms.PasswordInput, label='Password')
    class Meta:
        model = Client
        fields = ['userNm','userPass']


def clean_RegForm(self):
    cleanedUserName = self.cleaned_data.get('userNm')
    if Client.objects.filter(userNm=cleanedUserName).exists():
        errorMsg = u"Error occurred."
        raise ValidationError(errorMsg)
    else:
        return cleanedUserName

我正在提交密码,但是我没有收到密码。在

我做错什么了?在


Tags: py密码datareturnifrequestuserpasshashers
1条回答
网友
1楼 · 发布于 2024-09-30 01:23:26

嗯。。您正在创建哈希密码,但不会将其保存在任何位置。 而且,因为您要保存表单(继承自ModelForm),所以密码字段直接从密码表单字段保存。在

您可以重写save方法并将hashpass设置为密码。但我认为这里的最佳实践是使用UserCreationForm,它为您处理密码哈希(它将使用列表中的第一个密码哈希器)。在

这里有一些自定义表单的例子。在

伪代码:

在表单.py在

from django.contrib.auth.forms import UserCreationForm


class RegisterForm(UserCreationForm):
    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        # do not require password confirmation
        del self.fields['password2']

在视图.py在

^{pr2}$

相关问题 更多 >

    热门问题