Django allauth自定义模板没有哈希密码

问题描述 投票:2回答:2

我正在使用自己的自定义视图并继承自SignupView(在from allauth.account.views import SignupView中)我也使用自己的forms.py传递给我的自定义视图。它正在注册用户,但是它没有做的一件事是散列密码。它以用户的方式保存用户的密码。我怎样才能使密码作为哈希存储在表中?

forms.朋友

from .models import User
from django import forms

class RegisterForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password']

    username    = forms.CharField(label='Username', widget=forms.TextInput(attrs={'placeholder': 'Username:'}))
    email       = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={'placeholder': 'Email:'}))
    password    = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'placeholder': 'Password:'}))

views.朋友

from allauth.account.views import SignupView
from .forms import RegisterForm

class RegisterView(SignupView):
    form_class = RegisterForm
    template_name = 'oauth/auth_form.html'

项目urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^accounts/', include('oauth.urls')),  //app name I created where my custom sign up view is
    url(r'^profiles/', include('profiles.urls')),

    url(r'^accounts/', include('allauth.urls')),
]
python django
2个回答
2
投票

您的表单需要继承SignupForm,因为它的save()方法正在使用正确的方法来创建新用户。当你使用ModelForm时,save()方法将使用模型的正常初始化创建一个新的User对象,而User创建需要对密码进行特殊处理。

所以只需定义字段并将password更改为password1

from allauth.account.forms import SignupForm

class RegisterForm(SignupForm):
    username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'placeholder': 'Username:'}))
    email = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={'placeholder': 'Email:'}))
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'placeholder': 'Password:'}))

0
投票

你可以通过重写save来做

from django.contrib.auth.hashers import make_password

class RegisterForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password']

    username    = forms.CharField(label='Username', widget=forms.TextInput(attrs={'placeholder': 'Username:'}))
    email       = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={'placeholder': 'Email:'}))
    password    = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'placeholder': 'Password:'}))

    def save(self, commit=True):
        instance = super(RegisterForm, self).save(commit=False)
        if instance.password:
            instance.password = make_password(instance.password)
        if commit:
            instance.save()
        return instance
© www.soinside.com 2019 - 2024. All rights reserved.