Django验证方法不起作用

时间:2017-12-31 05:48:25

标签: python django

我正在尝试使用django.contrib.auth authenticate()方法中的默认Django来验证用户是否存在。我在用户注册后立即这样做。用户注册并将其用户名,电子邮件和密码输入到数据库中,但是当我呼叫authenticate(username=username, password=password)时,由于某种原因它正在返回None。密码存储为哈希值,值得注意的是我使用自己的自定义用户模型,但继承自django.contrib.auth用户模型。

以下是我的观点:

class RegisterView(SuccessMessageMixin, View):
    form_class = RegisterForm
    template_name = 'oauth/auth_form.html'
    success_message = "You have successfully created an account!"

    # Display blank form
    def get(self, request):
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():
            user = form.save(commit=False) # Do not save to table yet

            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            try:
                validate_password(password, user)

            except ValidationError as e:
                form.add_error('password', e)  # to be displayed with the field's errors
                return render(request, self.template_name, {'form': form})

            user.set_password(password)
            user.save()

            # Let's try to login the user
            user = authenticate(username=username, password=password)

            if user is not None:

                login(request, user)
                return redirect('http://google.com')


        return render(request, self.template_name, {'form': form})

为什么验证方法对我不起作用?

1 个答案:

答案 0 :(得分:0)

虽然@schwobaseggl的答案可以解决你的问题,即“不需要进行身份验证,只需直接登录”,但我在一个较旧的项目中做了类似的事情,也许对你有帮助。

此处注册过程自动登录用户,我们使用电子邮件令牌作为密码:

def get_or_create_user(mobile):
    UserModel = get_user_model()
    try:
        user = UserModel.objects.get(mobile=mobile)
    except UserModel.DoesNotExist:
        user = UserModel(mobile=mobile, username=mobile)
        user.set_unusable_password()
        user.save()
    return user

...

class UserRegistrationAndLogin(View):
    ...

    def post(self, request):
        form = self.form_class(request.POST)
        next_url = request.GET.get('next')
        if form.is_valid():
            entered_token = form.cleaned_data['otp']
            if entered_token == self.token:
                user = get_or_create_user(mobile=self.mobile)
                login(request, user)
                return redirect(next_url or settings.LOGIN_REDIRECT_URL)
            else:
                form.add_error('otp', 'OTP does not match!')
        return render(request, self.template_name, context={'form': form, 'mobile': self.mobile})