在 django_Restframework 中使用 AbstractUser 创建自定义用户模型
每个新的 Django 项目都应该使用自定义用户模型。 Django 官方文档说它是“强烈推荐的”,但我会更进一步,毫不犹豫地说:你不预先使用自定义用户模型是疯了。
为什么你需要在 Django 中自定义用户模型?
当您使用自定义用户模型开始您的项目时,请停止考虑这是否是您项目的正确选择。
将所有与用户相关的信息保存在一个模型中,无需额外或更复杂的数据库查询来检索相关模型。另一方面,将特定于应用程序的用户信息存储在与您的自定义用户模型有关系的模型中可能更合适。这允许每个应用程序指定自己的用户数据要求,而不会与其他应用程序的假设发生潜在冲突或破坏。这也意味着您将保持您的用户模型尽可能简单,专注于身份验证,并遵循 Django 期望自定义用户模型满足的最低要求。
所以我认为很清楚为什么我们需要在 django 中自定义用户模型,在本文中我们将学习如何在 django 中创建自定义用户模型及其 api
创建自定义用户模型的步骤
$ cd ~/Desktop$ mkdir code && cd code
$ pipenv install django
新建一个名为 login 的 Django 项目
$ django-admin startproject login
$ python manage.py startapp api
$ pipenv install rest_framework
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Add these lines to to your installed apps section in settings. py
'rest_framework',
'rest_framework.authtoken',
'api',
'rest_auth'
]
AUTH_USER_MODEL ='api.urls'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from datetime import date
class User(AbstractUser):
username = models.CharField(max_length = 50, blank = True, null = True, unique = True)
email = models.EmailField(_('email address'), unique = True)
native_name = models.CharField(max_length = 5)
phone_no = models.CharField(max_length = 10)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name']
def __str__(self):
return "{}".format(self.email)
admin.py
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .models import User
class UserAdmin(BaseUserAdmin):
form = UserChangeForm
fieldsets = (
(None, {'fields': ('email', 'password', )}),
(_('Personal info'), {'fields': ('first_name', 'last_name')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
(_('user_info'), {'fields': ('native_name', 'phone_no')}),
)
add_fieldsets = (
(None, {
'classes': ('wide', ),
'fields': ('email', 'password1', 'password2'),
}),
)
list_display = ['email', 'first_name', 'last_name', 'is_staff', "native_name", "phone_no"]
search_fields = ('email', 'first_name', 'last_name')
ordering = ('email', )
admin.site.register(User, UserAdmin)
serializers.py
from rest_framework import serializers
from api.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
urlpatterns = [
path('auth/', include('rest_auth.urls')),
]
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path(" ", include("api.urls"))
]
$ python manage.py makemigrations users
$ python manage.py migrate
$ python manage.py createsuperuser
Email address: test@test.com
Password:
Password (again):
Superuser created successfully.
$ python manage.py runserver