自定义账号模型类
# -*- coding: utf-8 -*-
from django.db import models
from django.utils import timezone
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import UserManager,AbstractBaseUser
from system.role.models import Role
class AccountManager(UserManager):
pass
class Account(AbstractBaseUser):
id = models.AutoField(primary_key=True)
username = models.CharField(max_length=150,unique=True)
role = models.ForeignKey(Role, on_delete=models.CASCADE)
contact = models.CharField(max_length=50)
email = models.CharField(max_length=100)
tel = models.CharField(max_length=20,blank=True,null=True)
is_active = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_staff = models.BooleanField(default=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=100)
date_joined = models.DateTimeField()
password_mtime = models.DateTimeField()
last_login = models.DateTimeField()
is_first_time_login = models.BooleanField(default=True)
objects = AccountManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
def set_password(self, raw_password):
self.password = make_password(raw_password)
self.password_mtime = timezone.now()
class Meta:
db_table = 't_account'
ordering = ('-id',)
def __str__(self):
return self.username
如下,我们就可以如下在view中,用 acctount对象.访问具体的属性:
def create(self, request, *args, **kwargs):
acct=self.request.user
logger.info('acct.role.type:%s' % acct.role.type)
logger.info('acct.is_superuser:%s' % acct.is_superuser)
logger.info('acct:%s' % acct)
logger.info('acct.username:%s' % acct.username)
request.user是一个对象,用户没有登陆的时候使用request.user.username会返回一个AnonymousUser,这是一个匿名用户,可是我在数据库中并没有这个用户。
总结:request.user 中的属性来自我们 自定义的账号模型中。
django中request.user的由来
参考URL: https://zhuanlan.zhihu.com/p/415424659
request.user哪里来的?
参考URL: https://www.cnblogs.com/wuchenggong/p/9675017.html