我调查了在DRF中的登录功能(django-rest-auth)

为了什么

使用DRF上的django-rest-auth实现快速用户认证。

实施环境

・Linux Mint (基于Ubuntu/Debian)
・Python ==> 3.7.0
・virtualenv ==> 20.0.15 (可选)
・Django ==> 3.0.5

预先安装软件包

请先设置Django REST Framework环境,然后进行django-rest-auth的配置。详情请参考https://www.django-rest-framework.org/。

$ pip install djangorestframework django-rest-authtoken

安装

安装软件包

$ pip install django-rest-auth

Successfully installed django-rest-auth-0.9.5
$ pip install django-allauth

Successfully installed defusedxml-0.6.0 django-allauth-0.41.0 oauthlib-3.1.0 python3-openid-3.1.0 requests-oauthlib-1.3.0

设置

    1. 将所需的内容(如rest_auth和django-allauth)添加到settings.py的INSTALLED_APPS中。

 

    https://github.com/Tivix/django-rest-auth/blob/master/docs/installation.rst
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'mysite.apps.MysiteConfig', 
    'mysite.templatetags.vendor',
    'rest_framework.authtoken',
    'rest_framework', 
    'django_filters'

    # -- ↓↓ ----- 以下を追加 ----- ↓↓ -- # 
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'rest_auth'
    'rest_auth.registration',
    # -------------------------------- #
]

SITE_ID = 1  #ついでにこれも追加します.

接下来,在url.py中添加登录认证路径。

urlpatterns = [
    ...,
    url(r'^rest-auth/', include('rest_auth.urls')), # -- 追加
    url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), # -- 追加
]

3. 数据库的迁移最后完成

$ python manage.py migrate

登录认证界面

qiita-rest-auth.png

一切正常地实现完毕。

自定义序列化器的设置。

想要删除登录认证页面的用户名等设置时,可以在setting.py中进行以下添加。

# REST_AUTHのシリアライザ設定
REST_AUTH_SERIALIZERS = {
        'LOGIN_SERIALIZER'      : ' Serializerクラスがあるパス.LoginSerializer',
}

#認証にユーザネームの要求を無くす
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True   
ACCOUNT_USERNAME_REQUIRED = False

我将创建一个自定义的登录序列化器。

请参考以下链接的本网站,制作一个序列化器:
https://github.com/Tivix/django-rest-auth/blob/master/docs/configuration.rst
https://github.com/Tivix/django-rest-auth/blob/master/rest_auth/serializers.py

这次我们只需要做一个简单的覆盖重写,即取消登录认证中的用户名。

from rest_auth.serializers import LoginSerializer as RestAuthLoginSerializer

class LoginSerializer(serializers.Serializer):
    username = None

更改结果

qiita-rest-login.png

输入用户名的表格消失了。
只需要登录,验证成功。

補充

^rest-auth/ ^password/reset/$ [name=’rest_password_reset’]
^rest-auth/ ^password/reset/confirm/$ [name=’rest_password_reset_confirm’]
^rest-auth/ ^login/$ [name=’rest_login’]
^rest-auth/ ^logout/$ [name=’rest_logout’]
^rest-auth/ ^user/$ [name=’rest_user_details’]
^rest-auth/ ^password/change/$ [name=’rest_password_change’]
^rest-auth/registration/