3

我创建了一个自定义用户注册表单,来自UserCreationForm. 当我尝试注册时,它确实注册成功,并且我可以看到一个新创建的用户,其中包含用户名及其电子邮件。但是该用户没有密码。

在管理员中,该用户的密码字段是No password set.。请纠正我哪里错了。谢谢你。

表格.py:

from album.forms import MyRegistrationForm

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class MyRegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2',)

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']

        if commit:
            user.save()

        return user

视图.py:

def register_user(request):
    if request.method == "POST":
        form = MyRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/accounts/register_success/')
    else:
        form = MyRegistrationForm()
    return render(request, 'register.html', {'form':form})
4

1 回答 1

4

当使用 对超类调用 save 时super,使用表单MyRegistrationForm,而不是其超类UserCreationForm

user = super(MyRegistrationForm, self).save(commit=False)
于 2013-10-29T10:46:24.667 回答