用户始终是 none,不允许用户登录

User is always none, doesn't allow the user to sign in

在创建登录和注册表单时,注册表单一直存在问题,问题是每当我通过注册创建用户并尝试使用测试用户登录时,它总是无法登录点我设置的Httpresponse。检查正在创建用户的管理面板后,现在我不知道去哪里,我确实认为我没有抓取正确的数据或者它没有抓取它


## Register
def register(request):
    if request.method == 'GET':
        return render(request, 'auth/register.html', { })
    if request.method == 'POST':
        form = RegistrationForm(request.POST)

        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            passwordConf = form.cleaned_data['passwordConf']
            email = form.cleaned_data['email']
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']

            user = User.objects.create_user(username, password, email)

            if password == passwordConf:
                return HttpResponseRedirect("/auth/signin")
            else:
                return HttpResponse("Passwords do not match", status=400)   
        else:
            return HttpResponse("Invalid registration request.(Bad Request)", status=400)

    else:
        form = RegistrationForm      
        return HttpResponse("Method not allowed on /auth/register.(Method Not Allowed)", status=405)


## Signin
def signin(request):
    if request.method == 'GET':
        return render(request, 'auth/signin.html', { })

    if request.method == 'POST':
        form = SigninForm(request.POST)

        if form.is_valid():
            username = request.POST["username"]
            password = request.POST["password"]
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login(request, user)
                return HttpResponseRedirect('/')
            else:
                return HttpResponse('Invalid Credientials', status=401 )
        else:
            return HttpResponse("Form is not valid", status=401)

可能是您的用户不活跃,即 is_activeFalse。你要么需要

AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend']

在您的设置中或将 is_active 设置为 True

DocsDefault backend 首先检查 is_active,这就是原因。

您的 create_user 发送的参数顺序与预期不同。根据 docs,它具有签名 create_user(username, email=None, password=None, **extra_fields).

目前,通过使用 user = User.objects.create_user(username, password, email),您正在设置 user.email=passworduser.password=email

您需要使用:

user = User.objects.create_user(username, email, password)