我有一个基于django表单的自定义用户模型和自定义登录页面:
my forms.py is:
from django import forms
class LoginForm(forms.Form):
Username = forms.CharField(widget=forms.TextInput(attrs={
'class': 'username-in',
'placeholder': 'enter your username...'
}))
Password = forms.CharField(widget=forms.TextInput(attrs={
'class': 'password-in',
'placeholder': 'enter your password...',
'type': 'password'
}))
在我的自定义用户模型中,我添加了如下字段:
from django.db import models
from django.contrib.auth.models import AbstractUser, User
class UserDetails(AbstractUser):
SuperUser = models.BooleanField(default=False)
BranchManager = models.BooleanField(default=False)
FinanceManager = models.BooleanField(default=False)
BranchName = models.ForeignKey('stock.Branch', null=True, blank=True, on_delete=models.CASCADE)
def __str__(self):
return self.first_name + " " + self.last_name
in my view.py for login:
from django.contrib.auth.hashers import make_password
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from users.forms import LoginForm
def LoginPage(request):
forms = LoginForm()
if request.method == 'POST':
forms = LoginForm(request.POST)
if forms.is_valid():
username = request.POST['Username']
password = request.POST['Password']
x = authenticate(username=username, password=password)
if x:
login(request, x)
return redirect('/stock')
context = {'form': forms}
return render(request, "users/login.html", context)
def UserRegister(request):
return render(request, 'users/register.html')
def LogoutPage(request):
logout(request)
return redirect('login')
用于检查数据是否来自表单,我使用print()函数查看将从表单接收的数据,用户名和密码应该是什么,但是当我打印(x)时,来自这一行——>'
x = authenticate(username=username, password=password)
'的结果是None, if语句不工作,用户无法登录。在项目的start .py中,我添加了这一行:
AUTH_USER_MODEL = 'users.UserDetails'
为什么django不验证用户并且在authenticate()中返回None ??
! !编辑更多信息:
我把views.py改成这样来声明用户并从db中获取get数据:
def LoginPage(request):
forms = LoginForm()
if request.method == 'POST':
forms = LoginForm(request.POST)
if forms.is_valid():
formusername = forms.cleaned_data['Username']
formpassword = forms.cleaned_data['Password']
x = UserDetails.objects.get(username=formusername)
username = x.username
password = x.password
print(formusername)
print(username)
print(formpassword)
print(password)
x = authenticate(username=username, password=password)
print(x)
if x:
login(request, x)
return redirect('/stock')
context = {'form': forms}
return render(request, "users/login.html", context)
,我的代码日志是:
System check identified no issues (0 silenced).
July 07, 2022 - 15:23:25
Django version 4.0.4, using settings 'Ngoci.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
moradi
moradi
r123456m123456
r123456m123456
None
在您的表单中您可以使用forms.PasswordInput
而不是TextInput
。https://docs.djangoproject.com/en/4.0/ref/forms/widgets/passwordinput
用户模型中的最好使用自定义权限(usermodel。branch_change usermodel。finance_change等)而不是额外的布尔字段(BranchManager, FinanceManager等)https://docs.djangoproject.com/en/4.0/topics/auth/customizing/定制权限
中的login最好使用django.contrib.auth中的LoginViewhttps://docs.djangoproject.com/en/4.0/topics/auth/default/django.contrib.auth.views.LoginView
我不知道你是如何在setup.py中设置授权的,但这不是你的情况。
密码。我认为你的工作问题你能检查一下如何在数据库中保存密码吗?如果您只保存用户,
user(**user_form.clened_data).save() # this is not works.
这是不工作没有make_password
:
user(**(user_form.clened_data | {password=make_password(user_form.clened_data['password'])} )).save()
之后,它应该工作。
附加:authenticate
取决于方法:
UserModel.objects.get_by_natural_key(username)
user.check_password(password)
getattr(user, 'is_active', True)
你可以在Django shell (python manage.py shell
)中检查:如果你没有从db接收到用户,或者其他方法返回False -这就是为什么你不能通过用户名和密码进行认证的答案。