Django login() 身份驗證總是返回 None (Django login() authenticate always returns None)


問題描述

Django login() 身份驗證總是返回 None (Django login() authenticate always returns None)

我已經編寫了這段代碼,它正確地註冊了用戶,但是當涉及到登錄功能時,它只適用於我在數據庫中擁有的超級用戶。每次我嘗試使用註冊表單登錄我喜歡的用戶時,身份驗證返回無。

我正在讓它打印表單數據,並且可以確認提交的表單具有準確的信息,但是除非我登錄超級用戶,否則每次都無法通過身份驗證。

查看次數:

def register(request):
    print(request.method)
    if request.method == 'POST':
        form = reg_form(request.POST)
        print(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            email = form.cleaned_data.get('email')
            phone = form.cleaned_data.get('phone')
            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')
            user = Users.objects.create(
                username=username, email=email,
                password=password, phone=phone,first_name=first_name, last_name=last_name
            )
            try:
                user = Users.objects.get(phone=form.cleaned_data.get('phone'))
                print("User exists")
            except Users.DoesNotExist:
                print("DoesNotExist")
                return render(request, 'register.html', {'form': reg_form})
            login(request, user)
            return render(request, 'profile.html')
        else:
            print(form.errors)
            return render(request, 'register.html', {'form': reg_form})
    else:
        return render(request, 'register.html', {'form': reg_form})


def log_in(request):
    if request.method == 'POST':
        form = log_form(request.POST)
        print(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(request, username=username, password=password)
            print(user)
            if user is not None:
                print("user exists")
                login(request, user)
                return render(request, 'profile.html')
            else:
                print("user does not exist")
                print(form.errors)
                return render(request, 'login.html', {
                    'form2': log_form
                })
        else:
            return render(request, 'login.html', {
            'form2': log_form
            })
    else:
        return render(request, 'login.html', {
            'form2': log_form
        })

註冊表單:

class reg_form(ModelForm):
    class Meta:
        model = Users
        fields = '__all__'
        widgets = { 'password': forms.PasswordInput(),
        }

登錄表格:

class log_form(forms.Form):
    username = forms.CharField(label='username', max_length=64)
    password = forms.CharField(widget=forms.PasswordInput)

參考解法

方法 1:

The password should be hashed: in Django the passwords are not stored in a readable format, but it stores the hash of that password. This concept is discussed in the changing password section of the documentation.

This thus means that for your reg_form, you save the object with:

class reg_form(ModelForm):
    class Meta:
        model = Users
        fields = '__all__'
        widgets = { 'password': forms.PasswordInput()}

    def save(*args, **kwargs):
        user = super().save(*args, **kwargs)
        user.set_password(user.password)
        return user

This is a very simple version of a more advanced form: the UserCreationForm perhaps it makes more sense, like @iklinac says, to subclass from that form, and slightly alter it to your specific model and fields.

方法 2:

Please check if the user is actually getting created in the database or not if the user is not getting created then make following changes to your register method:

use 'Users.objects.create_user' method instead of 'Users.objects.create', please find below link for more details:

https://docs.djangoproject.com/en/3.2/topics/auth/default/

Also hash your password as Willem is suggesting.

(by beatmaisterWillem Van OnsemJayantSeth)

參考文件

  1. Django login() authenticate always returns None (CC BY‑SA 2.5/3.0/4.0)

#authentication #Python #django-models #Django






相關問題

PHP Twitter OAuth - 我無法驗證我的帳戶 (PHP Twitter OAuth - I cannot authenticate my account)

如何設置 RIA 服務以使用現有的 ASP.Net 成員基礎 (How to setup RIA Services to use an existing ASP.Net membership base)

使用具有身份驗證的 URL 設置圖像-IOS SDK (Set Image With URL having authentication-IOS SDK)

支持 Facebook 的 Codeigniter 身份驗證庫 (Codeigniter Authentication library with Facebook support)

lighttpd:身份驗證後如何將端口(僅對本地主機可見)轉發到 WAN? (lighttpd: How to forward port (visible only to localhost) to WAN after authentication?)

Symfony 2.8 WebTestCase:無法創建登錄會話 (Symfony 2.8 WebTestCase: Cannot create logged-in session)

使用 facebook、twitter 等進行身份驗證。合而為一! (Authentication with facebook, twitter, etc.. all in one!)

默認情況下,ASP.NET 登錄控件是否使用 ReturnURL 進行重定向? (By default, does ASP.NET Login Control use the ReturnURL to redirect?)

發布/訂閱請求身份驗證作為服務(或通過服務密鑰)而不是 Auth0 臨時密鑰 (Pub/sub request authentication as a service (or by service key) instead of Auth0 temporary key)

通過 Nginx 進行 Haproxy 身份驗證 (Haproxy authentication through Nginx)

Django login() 身份驗證總是返回 None (Django login() authenticate always returns None)

laravel 微風 Multi Auth - 具有兩個不同註冊的 Admin Guard (laravel breeze Multi Auth - Admin Guard with two diffirent registration)







留言討論