Django 中的自定义验证

Django自带的验证机制足以应对一般情况,但是你可能不满足于默认的可立即使用的配置。在你的项目中自定义验证机制,需要了解在已有验证系统中哪些地方是可以扩展的,哪些地方是可以代替的。这个文档提供了如何自定义验证系统的一些细节。

<authentication-backends>当用户模型中存储的用户名和密码需要不同于Django默认服务的验证时,提供了一个可扩展系统。

你可以给你的模型 定制权限 并且可以被Django的授权系统通过检查。

你可以 :ref:` 扩展 <extending-user> ` 默认的 User 模型,或者完全自定义一个模型进行 :ref:` 替换 <auth-custom-user>`

其它认证资源

有时候你需要连接到其他认证源——一个包含用户名及密码的源或者认证方法。

例如,你的公司可能已经存在一套存储所有员工用户名及密码的 LDAP 配置。如果用户在LDAP和基于Django的应用程序中都有独立账号,那对用户自己或者网络管理员都会造成麻烦。

所以,为了处理这样的情况,Django认证系统可以让你插入其他认证源。您可以重写Django的默认基于数据库的方案,或者可以与其他系统一起使用默认系统。

请参阅<authentication-backends-reference>身份验证后端引用,有关Django中包含的身份验证后端的信息。

指定授权后端

在幕后,Django维护一个“身份验证后端”列表,用于检查身份验证。当有人调用:func:django.contrib.auth.authenticate() - 如下所示:ref:如何在`用户登录<how-to-log-a-user-in> - Django尝试所有身份验证后端进行身份验证。如果第一个验证方法失败,Django会尝试第二个验证方法,依此类推,直到所有后端都被尝试。

在设置:`AUTHENTICATION_BACKENDS`设置中指定要使用的身份验证后端列表。这应该是一个Python路径名列表,指向知道如何进行身份验证的Python类。这些类可以在你的Python路径上的任何地方。

默认, :setting:`AUTHENTICATION_BACKENDS`设定为:

['django.contrib.auth.backends.ModelBackend']

Django 的默认后台只检查其数据库和内置权限,并不提供任何登录限制机制来防止暴力登录攻击。如果需要抵制暴力登录攻击,需要自己在后台实现登录限制机制,或者使用 Web 服务器提供的保护机制。

:setting:`AUTHENTICATION_BACKENDS`是有序的,如果相同的用户名和密码对于多个后端都是合法的,那么 Django 会优先使用其中的第一个后端,而不会再处理后面的后端。

如果一个后端抛出 PermissionDenied 异常,则验证流程立马终止,Django 不会继续检查其后的后端。

Note

一旦用户通过验证,Django 会将之前用于验证该用户的后端保存在用户的 session 中,以便在将来(session 有效期内)需要访问当前已验证的用户时可以重用该后端。这个优化意味着在 session 中缓存了验证后端的源代码,因此,如果你修改了 AUTHENTICATION_BACKENDS 同时希望使用另外的方法重新验证用户,那么需要清除 session 数据。清除 session 数据的一个简单方法是执行 Session.objects.all().delete()

编写一个验证后端

一个验证后端其实就是一个 class,它实现了两个必要的方法:get_user(user_id)authenticate(request, **credentials),以及其它一系列可选的权限相关的方法:ref:`authorization methods<authorization_methods> `.

get_user 方法只接受一个参数``user_id``,user_id 有可能是 用户名、数据库 ID 或者其它任何值(该值必须是用户对象的主键),该方法返回一个用户对象。

authenticate``方法接受 ``request 参数和 credentials 关键字参数,大多数情况下,该方法类似于下面的代码:

class MyBackend:
    def authenticate(self, request, username=None, password=None):
        # Check the username/password and return a user.
        ...

但它也可能验证一个Token,就像这样:

class MyBackend:
    def authenticate(self, request, token=None):
        # Check the token and return a user.
        ...

无论是哪一种方式,authenticate()``都应该检查所获得的凭证,并当凭证有效时返回一个用户对象。当凭证无效时,应该返回``None

requestHttpRequest ,默认为 None 如果没有被提供给 authenticate() (它把request传给后端).

Django admin 和 Django User object. 紧密结合。最好的处理方式是为你后端的每一个用户都创建一个 Django User 。(例如, 你的 LDAP 目录、你的外部 SQL 数据库等等。) 你能写一个脚本来提前做这件事情,或者让你的 authenticate 方法在一个用户第一次登录时做这件事。

下面是一段验证后端的示例代码,它通过在 ``settings.py``文件中定义的用户名和密码变量进行身份验证,并且当用户第一次验证时,创建一个Django的``User``对象。

from django.conf import settings
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User

class SettingsBackend:
    """
    Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.

    Use the login name and a hash of the password. For example:

    ADMIN_LOGIN = 'admin'
    ADMIN_PASSWORD = 'pbkdf2_sha256$30000$Vo0VlMnkR4Bk$qEvtdyZRWTcOsCnI/oQ7fVOu1XAURIZYoOZ3iq8Dr4M='
    """

    def authenticate(self, request, username=None, password=None):
        login_valid = (settings.ADMIN_LOGIN == username)
        pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
        if login_valid and pwd_valid:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                # Create a new user. There's no need to set a password
                # because only the password from settings.py is checked.
                user = User(username=username)
                user.is_staff = True
                user.is_superuser = True
                user.save()
            return user
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
Changed in Django 1.11:

request 参数已经添加到 authenticate(),Django 2.1 将会移除不接受它的后端。

在自定义的后端处理授权

自定义的认证后端可以提供他们自己的权限。

用户模型会把权限查找函数(get_group_permissions(), get_all_permissions(), has_perm(), and has_module_perms())委托给任何实现了这些函数的验证后端。

用户所拥有的权限将是所有验证后端返回的所有权限的一个超集。也就是说,如果任何后端之一将一个权限赋予了用户,那么Django最终也将该权限赋予这个用户。

如果一个后端在:meth:~django.contrib.auth.models.User.has_perm()PermissionDenied() 异常,则鉴权过程将立刻失败退出,并且Django将不再检查随后的后端。

上面的简单后端可以相当容易的实现管理员权限:

class SettingsBackend:
    ...
    def has_perm(self, user_obj, perm, obj=None):
        return user_obj.username == settings.ADMIN_LOGIN

这将给予上例中被授权访问的用户以完全权限。注意,除了与对应的类 django.contrib.auth.models.User 函数相同的参数之外,后端的auth函数还接收user对象作为一个参数,这个user对象有可能是匿名user。

django/contrib/auth/backend.py 中的 ModelBackend 类给出了鉴权机制的全部实现,这个类是默认的后端并且在大多时候都需要 auth_permission 表。若需要对部分后端API的行为进行自定义,可以利用Python的继承,定义 ModelBackend 的子类,而不是在自定义后端中对所有API重新实现一遍。

匿名用户的授权

匿名用户是指那些没有验证过的用户,也就是说,他们没有提供任何有效的验证信息。然而,这并不一定意味着他们就无权做任何事。在最基本的层面上,大多数站点允许匿名用户浏览大部分页面,而且很多站点也允许匿名评论。

Django的权限框架并没有存储匿名用户的权限。然而,传给验证后端的用户对象可能是一个:class:`django.contrib.auth.models.AnonymousUser`对象,使得后端可以自定义对匿名用户的验证。这对于那些编写可复用应用的作者来讲格外有用,因为他们可以将验证完全委托给验证后端,而不是通过设置。比如,当控制匿名访问的时候。

未激活用户的授权

非活跃用户就是:attr:~django.contrib.auth.models.User.is_active`字段设置为``False``的用户。:class:`~django.contrib.auth.backends.ModelBackend 和:class:`~django.contrib.auth.backends.RemoteUserBackend`验证后台禁止这些用户进行验证。如果用户有:attr:`~django.contrib.auth.models.CustomUser.is_active`字段,则所有的用户都允许进行验证。

如果你想用非活跃用户来验证,你可以使用:class: ~django.contrib.auth.backends.AllowAllUsersModelBackend 和:class: ~django.contrib.auth.backends.AllowAllUsersRemoteUserBackend

权限系统支持匿名用户有权执行某些操作,而经过已验证的不活动用户则不能这样做。

在你的后端permission方法中,不要忘记测试user的``is_active``属性。

处理对象权限

Django的权限框架为对象权限提供了基础,尽管在内核中没有实现它。这意味着检查对象权限将始终返回``False``或空列表(取决于所执行的检查)。身份验证后端将为每个对象相关的授权方法接收关键字参数``obj``和``user_obj``,并可以适当地返回对象级权限。

自定义权限

为给定的模型对象创建自定权限,使用 permission , 参考: model Meta attribute<meta-options>

这个 Task 模型创建了三个用户自定权限,即:用户能不能使用 Task 实例执行操作,取决于你的应用程序。

class Task(models.Model):
    ...
    class Meta:
        permissions = (
            ("view_task", "Can see available tasks"),
            ("change_task_status", "Can change the status of tasks"),
            ("close_task", "Can remove a task by setting its status as closed"),
        )

当你运行:djadmin:manage.py migrate <migrate> 时,它只创建那些额外的权限。(创建权限的函数连接到:data:~django.db.models.signals.post_migrate 信号)。 你的代码负责在用户试图访问由应用程序提供的功能(查看任务(task),改变任务状态,关闭任务)时检查这些权限的值。继续上面的例子, 下面的语句检查是否一个用户能查看任务:

user.has_perm('app.view_task')

扩展现有的用户(User)模型

There are two ways to extend the default User model without substituting your own model. If the changes you need are purely behavioral, and don't require any change to what is stored in the database, you can create a proxy model based on User. This allows for any of the features offered by proxy models including default ordering, custom managers, or custom model methods.

If you wish to store information related to User, you can use a OneToOneField to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user. For example you might create an Employee model:

from django.contrib.auth.models import User

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    department = models.CharField(max_length=100)

假设一个既有用户又有雇员模型的现有雇员Fred Smith,您可以使用Django的标准相关模型约定访问相关信息:

>>> u = User.objects.get(username='fsmith')
>>> freds_department = u.employee.department

To add a profile model's fields to the user page in the admin, define an InlineModelAdmin (for this example, we'll use a StackedInline) in your app's admin.py and add it to a UserAdmin class which is registered with the User class:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User

from my_user_profile_app.models import Employee

# Define an inline admin descriptor for Employee model
# which acts a bit like a singleton
class EmployeeInline(admin.StackedInline):
    model = Employee
    can_delete = False
    verbose_name_plural = 'employee'

# Define a new User admin
class UserAdmin(BaseUserAdmin):
    inlines = (EmployeeInline, )

# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

These profile models are not special in any way - they are just Django models that happen to have a one-to-one link with a user model. As such, they aren't auto created when a user is created, but a django.db.models.signals.post_save could be used to create or update related models as appropriate.

Using related models results in additional queries or joins to retrieve the related data. Depending on your needs, a custom user model that includes the related fields may be your better option, however, existing relations to the default user model within your project's apps may justify the extra database load.

取代了一个用户 User 模型。

Some kinds of projects may have authentication requirements for which Django's built-in User model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username.

Django 允许你为引用了自定模型的:setting: AUTH_USER_MODEL 设置一个值来重写默认的用户表。

AUTH_USER_MODEL = 'myapp.MyUser'

This dotted pair describes the name of the Django app (which must be in your INSTALLED_APPS), and the name of the Django model that you wish to use as your user model.

启动一个项目的时候使用一个自定的用户模型

If you're starting a new project, it's highly recommended to set up a custom user model, even if the default User model is sufficient for you. This model behaves identically to the default user model, but you'll be able to customize it in the future if the need arises:

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass

Don't forget to point AUTH_USER_MODEL to it. Do this before creating any migrations or running manage.py migrate for the first time.

同样的,在 app 中的 admin.py 中注册模型。

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User

admin.site.register(User, UserAdmin)

在项目中更改为自定义用户模型。

Changing AUTH_USER_MODEL after you've created database tables is significantly more difficult since it affects foreign keys and many-to-many relationships, for example.

This change can't be done automatically and requires manually fixing your schema, moving your data from the old user table, and possibly manually reapplying some migrations. See #25313 for an outline of the steps.

Due to limitations of Django's dynamic dependency feature for swappable models, the model referenced by AUTH_USER_MODEL must be created in the first migration of its app (usually called 0001_initial); otherwise, you'll have dependency issues.

In addition, you may run into a CircularDependencyError when running your migrations as Django won't be able to automatically break the dependency loop due to the dynamic dependency. If you see this error, you should break the loop by moving the models depended on by your user model into a second migration. (You can try making two normal models that have a ForeignKey to each other and seeing how makemigrations resolves that circular dependency if you want to see how it's usually done.)

应用复用和 AUTH_USER_MODEL

Reusable apps shouldn't implement a custom user model. A project may use many apps, and two reusable apps that implemented a custom user model couldn't be used together. If you need to store per user information in your app, use a ForeignKey or OneToOneField to settings.AUTH_USER_MODEL as described below.

Referencing the User model

If you reference User directly (for example, by referring to it in a foreign key), your code will not work in projects where the AUTH_USER_MODEL setting has been changed to a different user model.

get_user_model()[source]

Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model(). This method will return the currently active user model -- the custom user model if one is specified, or User otherwise.

When you define a foreign key or many-to-many relations to the user model, you should specify the custom model using the AUTH_USER_MODEL setting. For example:

from django.conf import settings
from django.db import models

class Article(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )

When connecting to signals sent by the user model, you should specify the custom model using the AUTH_USER_MODEL setting. For example:

from django.conf import settings
from django.db.models.signals import post_save

def post_save_receiver(sender, instance, created, **kwargs):
    pass

post_save.connect(post_save_receiver, sender=settings.AUTH_USER_MODEL)

Generally speaking, it's easiest to refer to the user model with the AUTH_USER_MODEL setting in code that's executed at import time, however, it's also possible to call get_user_model() while Django is importing models, so you could use models.ForeignKey(get_user_model(), ...).

If your app is tested with multiple user models, using @override_settings(AUTH_USER_MODEL=...) for example, and you cache the result of get_user_model() in a module-level variable, you may need to listen to the setting_changed signal to clear the cache. For example:

from django.apps import apps
from django.contrib.auth import get_user_model
from django.core.signals import setting_changed
from django.dispatch import receiver

@receiver(setting_changed)
def user_model_swapped(**kwargs):
    if kwargs['setting'] == 'AUTH_USER_MODEL':
        apps.clear_cache()
        from myapp import some_module
        some_module.UserModel = get_user_model()
Changed in Django 1.11:

The ability to call get_user_model() at import time was added.

指定自定义用户模型

Model 设计注意事项

在处理与您的自定义用户模型中不直接与身份验证相关的信息之前要仔细考虑。

在与用户模型有关系的模型中存储特定于应用程序的用户信息可能更好。这允许每个应用程序指定自己的用户数据需求,而不冒与其他应用程序发生冲突的风险。另一方面,检索此相关信息的查询将涉及数据库连接,这可能对性能产生影响。

Django 希望你自定义的用户模型能够满足一些最低需求。

如果使用默认身份验证后端,那么您的模型必须具有用于标识目的的唯一字段。这可以是用户名、电子邮件地址或任何其他唯一属性。如果使用可以支持它的自定义身份验证后端,则允许使用非唯一用户名字段。

构造一个兼容的自定义用户模型的最简单方法是继承:class:~django.contrib.auth.models.AbstractBaseUser。:class:`~django.contrib.auth.models.AbstractBaseUser`提供用户模型的核心实现,包括散列密码和标记化的密码重置。然后必须提供一些关键实现细节:

class models.CustomUser
USERNAME_FIELD

作为唯一标识符的描述用户模型字段名的字符串,通常是一个用户名,但也可以是一个电子邮件地址,或任何其他唯一标识符。该字段*必须*是唯一的(即定义了 unique=True ),除非你使用自定义身份验证后端,可以支持非唯一的用户名。

接下来的样例中,identifier 字段将被用作识别字段。

class MyUser(AbstractBaseUser):
    identifier = models.CharField(max_length=40, unique=True)
    ...
    USERNAME_FIELD = 'identifier'

USERNAME_FIELD now supports ForeignKeys. Since there is no way to pass model instances during the createsuperuser prompt, expect the user to enter the value of to_field value (the primary_key by default) of an existing instance.

EMAIL_FIELD
New in Django 1.11.

A string describing the name of the email field on the User model. This value is returned by get_email_field_name().

REQUIRED_FIELDS

A list of the field names that will be prompted for when creating a user via the createsuperuser management command. The user will be prompted to supply a value for each of these fields. It must include any field for which blank is False or undefined and may include additional fields you want prompted for when a user is created interactively. REQUIRED_FIELDS has no effect in other parts of Django, like creating a user in the admin.

比如说,这里是一个局部的用户模型,定义了两个必须的字段——生日和身高。

class MyUser(AbstractBaseUser):
    ...
    date_of_birth = models.DateField()
    height = models.FloatField()
    ...
    REQUIRED_FIELDS = ['date_of_birth', 'height']

Note

REQUIRED_FIELDS must contain all required fields on your user model, but should not contain the USERNAME_FIELD or password as these fields will always be prompted for.

REQUIRED_FIELDS now supports ForeignKeys. Since there is no way to pass model instances during the createsuperuser prompt, expect the user to enter the value of to_field value (the primary_key by default) of an existing instance.

is_active

A boolean attribute that indicates whether the user is considered "active". This attribute is provided as an attribute on AbstractBaseUser defaulting to True. How you choose to implement it will depend on the details of your chosen auth backends. See the documentation of the is_active attribute on the built-in user model for details.

get_full_name()

Optional. A longer formal identifier for the user such as their full name. If implemented, this appears alongside the username in an object's history in django.contrib.admin.

get_short_name()

Optional. A short, informal identifier for the user such as their first name. If implemented, this replaces the username in the greeting to the user in the header of django.contrib.admin.

Changed in Django 2.0:

In older versions, subclasses are required to implement get_short_name() and get_full_name() as AbstractBaseUser has implementations that raise NotImplementedError.

引入 AbstractBaseUser

AbstractBaseUser and BaseUserManager are importable from django.contrib.auth.base_user so that they can be imported without including django.contrib.auth in INSTALLED_APPS.

The following attributes and methods are available on any subclass of AbstractBaseUser:

class models.AbstractBaseUser
get_username()

Returns the value of the field nominated by USERNAME_FIELD.

clean()

Normalizes the username by calling normalize_username(). If you override this method, be sure to call super() to retain the normalization.

classmethod get_email_field_name()
New in Django 1.11.

Returns the name of the email field specified by the EMAIL_FIELD attribute. Defaults to 'email' if EMAIL_FIELD isn't specified.

classmethod normalize_username(username)

Applies NFKC Unicode normalization to usernames so that visually identical characters with different Unicode code points are considered identical.

is_authenticated

Read-only attribute which is always True (as opposed to AnonymousUser.is_authenticated which is always False). This is a way to tell if the user has been authenticated. This does not imply any permissions and doesn't check if the user is active or has a valid session. Even though normally you will check this attribute on request.user to find out whether it has been populated by the AuthenticationMiddleware (representing the currently logged-in user), you should know this attribute is True for any User instance.

is_anonymous

Read-only attribute which is always False. This is a way of differentiating User and AnonymousUser objects. Generally, you should prefer using is_authenticated to this attribute.

set_password(raw_password)

Sets the user's password to the given raw string, taking care of the password hashing. Doesn't save the AbstractBaseUser object.

When the raw_password is None, the password will be set to an unusable password, as if set_unusable_password() were used.

check_password(raw_password)

Returns True if the given raw string is the correct password for the user. (This takes care of the password hashing in making the comparison.)

set_unusable_password()

Marks the user as having no password set. This isn't the same as having a blank string for a password. check_password() for this user will never return True. Doesn't save the AbstractBaseUser object.

You may need this if authentication for your application takes place against an existing external source such as an LDAP directory.

has_usable_password()

Returns False if set_unusable_password() has been called for this user.

get_session_auth_hash()

Returns an HMAC of the password field. Used for Session invalidation on password change.

AbstractUser subclasses AbstractBaseUser:

class models.AbstractUser
clean()
New in Django 1.11.

Normalizes the email by calling BaseUserManager.normalize_email(). If you override this method, be sure to call super() to retain the normalization.

You should also define a custom manager for your user model. If your user model defines username, email, is_staff, is_active, is_superuser, last_login, and date_joined fields the same as Django's default user, you can just install Django's UserManager; however, if your user model defines different fields, you'll need to define a custom manager that extends BaseUserManager providing two additional methods:

class models.CustomUserManager
create_user(*username_field*, password=None, **other_fields)

The prototype of create_user() should accept the username field, plus all required fields as arguments. For example, if your user model uses email as the username field, and has date_of_birth as a required field, then create_user should be defined as:

def create_user(self, email, date_of_birth, password=None):
    # create user here
    ...
create_superuser(*username_field*, password, **other_fields)

The prototype of create_superuser() should accept the username field, plus all required fields as arguments. For example, if your user model uses email as the username field, and has date_of_birth as a required field, then create_superuser should be defined as:

def create_superuser(self, email, date_of_birth, password):
    # create superuser here
    ...

Unlike create_user(), create_superuser() must require the caller to provide a password.

BaseUserManager provides the following utility methods:

class models.BaseUserManager
classmethod normalize_email(email)

Normalizes email addresses by lowercasing the domain portion of the email address.

get_by_natural_key(username)

Retrieves a user instance using the contents of the field nominated by USERNAME_FIELD.

make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')

Returns a random password with the given length and given string of allowed characters. Note that the default value of allowed_chars doesn't contain letters that can cause user confusion, including:

  • i, l, I, and 1 (lowercase letter i, lowercase letter L, uppercase letter i, and the number one)
  • o, O, and 0 (lowercase letter o, uppercase letter o, and zero)

Extending Django's default User

If you're entirely happy with Django's User model and you just want to add some additional profile information, you could simply subclass django.contrib.auth.models.AbstractUser and add your custom profile fields, although we'd recommend a separate model as described in the "Model design considerations" note of 指定自定义用户模型. AbstractUser provides the full implementation of the default User as an abstract model.

自定义用户和内建的auth表单

Django's built-in forms and views make certain assumptions about the user model that they are working with.

The following forms are compatible with any subclass of AbstractBaseUser:

The following forms make assumptions about the user model and can be used as-is if those assumptions are met:

  • PasswordResetForm: Assumes that the user model has a field that stores the user's email address with the name returned by get_email_field_name() (email by default) that can be used to identify the user and a boolean field named is_active to prevent password resets for inactive users.

Finally, the following forms are tied to User and need to be rewritten or extended to work with a custom user model:

If your custom user model is a simple subclass of AbstractUser, then you can extend these forms in this manner:

from django.contrib.auth.forms import UserCreationForm
from myapp.models import CustomUser

class CustomUserCreationForm(UserCreationForm):

    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = UserCreationForm.Meta.fields + ('custom_field',)

Custom users and django.contrib.admin

If you want your custom user model to also work with the admin, your user model must define some additional attributes and methods. These methods allow the admin to control access of the user to admin content:

class models.CustomUser
is_staff

如果允许用户有访问 admin 页面就返回 True

is_active

返回``True``,如果该用户的账号当前是激活状态

has_perm(perm, obj=None):

Returns True if the user has the named permission. If obj is provided, the permission needs to be checked against a specific object instance.

has_module_perms(app_label):

Returns True if the user has permission to access models in the given app.

You will also need to register your custom user model with the admin. If your custom user model extends django.contrib.auth.models.AbstractUser, you can use Django's existing django.contrib.auth.admin.UserAdmin class. However, if your user model extends AbstractBaseUser, you'll need to define a custom ModelAdmin class. It may be possible to subclass the default django.contrib.auth.admin.UserAdmin; however, you'll need to override any of the definitions that refer to fields on django.contrib.auth.models.AbstractUser that aren't on your custom user class.

自定义用户和权限。

To make it easy to include Django's permission framework into your own user class, Django provides PermissionsMixin. This is an abstract model you can include in the class hierarchy for your user model, giving you all the methods and database fields necessary to support Django's permission model.

PermissionsMixin provides the following methods and attributes:

class models.PermissionsMixin
is_superuser

Boolean. Designates that this user has all permissions without explicitly assigning them.

get_group_permissions(obj=None)

Returns a set of permission strings that the user has, through their groups.

If obj is passed in, only returns the group permissions for this specific object.

get_all_permissions(obj=None)

Returns a set of permission strings that the user has, both through group and user permissions.

If obj is passed in, only returns the permissions for this specific object.

has_perm(perm, obj=None)

Returns True if the user has the specified permission, where perm is in the format "<app label>.<permission codename>" (see permissions). If the user is inactive, this method will always return False.

If obj is passed in, this method won't check for a permission for the model, but for this specific object.

has_perms(perm_list, obj=None)

Returns True if the user has each of the specified permissions, where each perm is in the format "<app label>.<permission codename>". If the user is inactive, this method will always return False.

If obj is passed in, this method won't check for permissions for the model, but for the specific object.

has_module_perms(package_name)

Returns True if the user has any permissions in the given package (the Django app label). If the user is inactive, this method will always return False.

PermissionsMixinModelBackend

If you don't include the PermissionsMixin, you must ensure you don't invoke the permissions methods on ModelBackend. ModelBackend assumes that certain fields are available on your user model. If your user model doesn't provide those fields, you'll receive database errors when you check permissions.

自定义用户和代理模型

One limitation of custom user models is that installing a custom user model will break any proxy model extending User. Proxy models must be based on a concrete base class; by defining a custom user model, you remove the ability of Django to reliably identify the base class.

If your project uses proxy models, you must either modify the proxy to extend the user model that's in use in your project, or merge your proxy's behavior into your User subclass.

一个完整的例子

Here is an example of an admin-compliant custom user app. This user model uses an email address as the username, and has a required date of birth; it provides no permission checking, beyond a simple admin flag on the user account. This model would be compatible with all the built-in auth forms and views, except for the user creation forms. This example illustrates how most of the components work together, but is not intended to be copied directly into projects for production use.

This code would all live in a models.py file for a custom authentication app:

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)


class MyUserManager(BaseUserManager):
    def create_user(self, email, date_of_birth, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
            date_of_birth=date_of_birth,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, date_of_birth, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            email,
            password=password,
            date_of_birth=date_of_birth,
        )
        user.is_admin = True
        user.save(using=self._db)
        return user


class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    date_of_birth = models.DateField()
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['date_of_birth']

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin

Then, to register this custom user model with Django's admin, the following code would be required in the app's admin.py file:

from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from customauth.models import MyUser


class UserCreationForm(forms.ModelForm):
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = MyUser
        fields = ('email', 'date_of_birth')

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class UserChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = MyUser
        fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin')

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial["password"]


class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('email', 'date_of_birth', 'is_admin')
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('date_of_birth',)}),
        ('Permissions', {'fields': ('is_admin',)}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'date_of_birth', 'password1', 'password2')}
        ),
    )
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ()

# Now register the new UserAdmin...
admin.site.register(MyUser, UserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)

Finally, specify the custom model as the default user model for your project using the AUTH_USER_MODEL setting in your settings.py:

AUTH_USER_MODEL = 'customauth.MyUser'