在 Django official guide ,内容如下:
Inside this
django.contrib.auth
model, there is aUser
class, who has following attributes (username, password, email, first_name, last_name).
我在github查看源码时,在django.contrib.auth
中并没有找到这个定义。
我只能在 django/contrib/auth/base_user.py
on this link 中看到 class AbstractBaseUser(models.Model):
,以及 django/contrib/auth/models.py
中的 class User(AbstractUser):
in this webpage .
Q1:上面官方文档中的class models.User
是什么意思,它意味着User
是models.py
下的一个类?
问题2:如果上述正确,那么User
类从哪里获取用户名、电子邮件等属性?
最佳答案
Q1: what does class models.User mean in above official document, it means User is a class under models.py?
在 Django 中,one 指的是带有 <i>app_name</i>.<i>ModelName</i>
的模型。 。因此,如果您指定模型,则会在 <i>app_name</i>/models.py
中实现。 ,但由于模型是在 models.py
中定义的文件中,将其包含在模型名称中是没有意义的。
例如 AUTH_USER_MODEL
setting [Django-doc] 的默认值是 auth.User
,因为应用程序的名称是 auth
,模型名称为User
.
Q2: if above is right, then where User class get attributes such as username, email etc?
通过继承。事实上,如果我们看一下 source code of the models.py
file [GitHub] ,我们看到:
class User(<b>AbstractUser</b>): """ Users within the Django authentication system are represented by this model. Username and password are required. Other fields are optional. """ class Meta(AbstractUser.Meta): swappable = 'AUTH_USER_MODEL'
和 AbstractUser
model [GitHub]定义 username
的字段, email
等:
class AbstractUser(AbstractBaseUser, PermissionsMixin): # … <b>username</b> = models.CharField( _('username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) <b>first_name</b> = models.CharField(_('first name'), max_length=150, blank=True) <b>last_name</b> = models.CharField(_('last name'), max_length=150, blank=True) <b>email</b> = models.EmailField(_('email address'), blank=True) <b>is_staff</b> = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.'), ) <b>is_active</b> = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) <b>date_joined</b> = models.DateTimeField(_('date joined'), default=timezone.now) # …
AbstractUser
是一个抽象模型。这意味着 Django 不会为其创建表。因此,从抽象表继承的模型将继承字段、方法等,然后这些字段将在从 AbstractUser
继承的模型上定义。 .
关于django - django.contrib.auth.User在Django源代码中定义在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67946439/