Django - Authenticate不会向用户添加后端

时间:2017-09-07 18:34:10

标签: django django-authentication

我创建了一个注册表单虽然成功创建了一个用户但无法登录,因为authenticate无法分配后端,即使用户被标记为is_authenticated=True
我使用身份验证的方式有什么不正确的地方吗? (注意我正在使用django all_auth,但不确定这是否会产生影响?)

在login()时,它产生了这个错误:

ValueError:You have multiple authentication backends configured and therefore must provide the backend argument or set the backend attribute on the user.

视图:

....
form = ProfileForm(request.POST)
    if form.is_valid():
        user_profile, user = form.save()
        authenticate(request, user=form.cleaned_data['email'],
                     password=form.cleaned_data['password1'])
        login(request, user)

models.py

class User(AbstractUser):
    def __str__(self):
        return self.username

    def get_absolute_url(self):
        return reverse('users:detail', kwargs={'username': self.username})


class UserProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    TITLE_CHOICES = (
        .....
    )
    title = models.CharField(max_length=5, null=True, choices=TITLE_CHOICES)
    date_of_birth = models.DateField()
    primary_phone = PhoneNumberField()
    EMPLOYMENT_CHOICES = (
        (....,...)
    )
    employment_status = models.CharField(max_length=35, choices=EMPLOYMENT_CHOICES)

个人资料表格:

class ProfileForm(allauthforms.SignupForm):
    title = FieldBuilder(UserProfile, 'title', )

    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)

    date_of_birth = FieldBuilder(UserProfile, 'date_of_birth', widget=SelectDateWidget())
    primary_phone = FieldBuilder(UserProfile, 'primary_phone')

    employment_status = FieldBuilder(UserProfile, 'employment_status')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["employment_status"].choices = [("", "---- Select your Employment Status ----"), ] + list(
            self.fields["employment_status"].choices)[1:]


    def save(self, *args):
        data = self.cleaned_data
        user = User.objects.create_user(
            username=data['email'],
            email=data['email'],
            password=data['password1'],
            first_name=data['first_name'],
            last_name=data['last_name'],
        )
        instance = UserProfile.objects.create(
            user=user,
            date_of_birth=data['date_of_birth'],
            primary_phone=data['primary_phone'],
            title=data['title'],
            employment_status=data['employment_status'],
        )
        return instance, user

1 个答案:

答案 0 :(得分:2)

当您致电authenticate时,如果验证成功,它将返回用户。致电login时,您应该使用此用户。

user = authenticate(request, username=form.cleaned_data['email'],
                    password=form.cleaned_data['password1'])
login(request, user)

请注意,除非您拥有自定义身份验证后端,否则应传递username而不是user

在Django 1.10+中,如果您已拥有用户实例,则不必调用authenticate。当您致电login时,您可以将后端作为参数提供,例如:

login(request, user, backend='django.contrib.auth.backends.ModelBackend')

有关详细信息,请参阅selecting the authentication backend上的文档。

相关问题