为什么我不能使用UserCreationForm在Django中创建自定义用户?

时间:2016-06-18 15:09:02

标签: python django forms registration

我可以通过导入自定义用户模型从shell创建用户,但是在提交表单后应用相同的方法时,不会创建用户。 以下是我的自定义用户模型的代码UserCreationForm和视图。

//model.py
class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique = True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)

objects = MyUserManager()

USERNAME_FIELD = 'email'


def get_full_name(self):
    # The user is identified by their email address
    return self.email


def get_short_name(self):
    # The user is identified by their email address
    return self.email


def __str__(self):  # __unicode__ on Python 2
    return self.email


def has_perm(self, perm, obj=None):
    "Does the user have a specific permission?"
    # Simplest possible answer: Yes, always
    return True


def has_module_perms(self, app_label):
    "Does the user have permissions to view the app `app_label`?"
    # Simplest possible answer: Yes, always
    return True


@property
def is_staff(self):
    "Is the user a member of staff?"
    # Simplest possible answer: All admins are staff
    return self.is_admin

我按照Django文档中的建议扩展了AbstractBaseUser以创建自定义用户模型。

//forms.py
class UserCreationForm(forms.ModelForm):
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    email = forms.EmailField(
        label='Email',
        widget=forms.EmailInput,
        required=True,
    )
    password1 = forms.CharField(
        label='Password',
        widget=forms.PasswordInput,
        required=True
    )
    password2 = forms.CharField(
        label='Password confirmation',
        widget=forms.PasswordInput,
        required=True
    )

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

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

我做错了表单处理吗? form.save()方法对我来说没有用。此外,文档也没有彻底讨论用户注册。我不知道为什么。

//views.py
def login(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = authenticate(email=request.POST['email'],
                                password=request.POST['password'])
            if user is not None:
                if user.is_active:
                    django_login(request, user)
                    return redirect('/home/', permanent=True)

    else:
        form = AuthenticationForm()
    return render(request, 'buymeauth/login.html', {'form': form})

    def register(request):
        user = request.user

    if request.method == 'POST':
        form = UserCreationForm(data=request.POST)
        if form.is_valid():
            my_user = MyUser(user.email, user.password)
            my_user.save()

            return redirect('/home/', permanent=True)
    else:
        form = UserCreationForm()

    return render(request, 'buymeauth/register.html', {'form': form})

我是Django的新手,但不是网络开发的新手。我和MEAN有一些接触,但我发现Django很难。我已经坚持使用这种认证和授权的东西5天了。

1 个答案:

答案 0 :(得分:0)

def register(request):
    # this is the logged-in user
    user = request.user    

    if request.method == 'POST':
        # this is the form with the submitted data
        form = UserCreationForm(data=request.POST)

        if form.is_valid():
            # the submitted data is correct
            my_user = MyUser(user.email, user.password)    

            # this is a new user with the same email and password 
            # than the currently logged-in user. It's not what you want
            # and it won't work if you're not logged-in
            my_user.save()

            return redirect('/home/', permanent=True)
    else:
        form = UserCreationForm()

    return render(request, 'buymeauth/register.html', {'form': form})

相反,你可能想要这个:

if request.method == 'POST':
    form = UserCreationForm(data=request.POST)
    if form.is_valid():
        user = form.save(commit=False)
        user.is_active = True    # if you want to skip email validation
        user.email = User.objects.normalize_email(user.email)
        user.save()