登录后,我想随时访问用户详细信息(特别是在导航栏中)。我没有使用django提供的用户模型。为了验证,我创建了自己的模型。我的数据库存储在phpmyadmin(Xampp)上的mysql。
AdminUser模型class adminUser(models.Model):
username=models.CharField(max_length=50)
firstname=models.CharField(max_length=50)
department=models.CharField(max_length=50)
name=models.CharField(max_length=50)
mail=models.CharField(max_length=50)
id=models.IntegerField(primary_key=True)
password=models.CharField(max_length=200)
class Meta:
db_table="admin_users"
admin_users.py
def login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if username is not None and password is not None:
user=adminUser.objects.get(username=username)
hashed_password = user.password
is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8'))
print(is_check)
if is_check==True:
return redirect(reverse('faq_index'))
else:
return render(request,'AdminUsers/login.html')
return render(request,'AdminUsers/login.html')
在登录过程中,用户详细信息只能通过登录功能访问,但我想在导航栏的所有页面中访问用户详细信息,还想知道用户是否经过认证。因为我没有使用django中定义的用户模型,所以我不能使用User .is_authenticated()。我该怎么做呢?
首先,从AbstractBaseUser
继承用户模型。它提供了一些功能,如is_authenticated
,set_password
等
然后在settings.py
中将您的自定义用户模型定义为AUTH_USER_MODEL
之后,django把你的自定义用户作为默认用户
models.py
from django.contrib.auth.base_user import AbstractBaseUser
class CustomUser(AbstractBaseUser):
...
settings.py
AUTH_USER_MODEL = 'myapp.MyUser'
Docs in https://docs.djangoproject.com/en/3.2/topics/auth/customizing/
我建议您退一步,扩展内置的User模型,而不是创建您自己的。
正如@Amin所提到的,您可以扩展AbstractBaseUser
类来创建自定义用户模型,并在settings.py
中覆盖AUTH_USER_MODEL
。
但是,您可以轻松地添加一个与内置User模型具有一对一关系的Profile
模型,该模型不需要任何覆盖(目前哪种方法更好,但我使用以下方法没有问题):
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models
UserModel = get_user_model()
class Profile(models.Model):
user = models.OneToOneField(UserModel, on_delete=models.CASCADE)
# add your desired fields here
department=models.CharField(max_length=50)
然后,在包含models.py
的文件夹中创建一个名为signals.py
的文件,并添加以下代码:
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Profile
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_user_settings(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
当一个User
对象被创建时,这将触发一个新的Profile
对象的创建。
然后,将以下内容添加到同一文件夹的apps.py
(假设应用程序的名称是users
…使其与包含Profile
模型的应用程序的名称相匹配):
from django.apps import AppConfig
class UsersConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'users'
def ready(self):
import users.signals
现在,在运行迁移之后,您将能够使用内置的User
模型,并在Profile
模型中根据需要向其添加额外的字段。
唯一的缺点是,如果你想在同一页面上修改User
模型和Profile
模型,它将需要一点额外的工作。您将不能仅仅在UpdateView
中指定模型名称。
我不记得我在哪里找到这个方法。我相信这是改编自simpleisbetterthancomplex.com这个页面,但我不是100%确定。
无论如何,Django会自动为你创建一个主键id
,所以你可能不需要在你的模型中手动定义它。