Django rest framework如何自定义用户表
作者:小龙狗 发布时间:2022-03-12 01:15:02
说明
Django 默认的用户表 auth_user
包含 id, password, last_login, is_superuser, username, last_name, email, is_staff, is_active, date_joined, first_name 字段。这些基本字段不够用时,在此基本表上拓展字段是很好选择。本文介绍在 DRF(Django Rest Framework) 上使用自定义用户表进行接口访问控制的功能设计。
1. Django项目和应用创建
先装必要的模块
pip install django
pip install djangorestframework
创建项目文件夹、项目和应用
E:\SweetYaya> mkdir MyProj01
E:\SweetYaya> cd MyProj01
E:\SweetYaya\MyProj01> django-admin startproject MyProj01 .
E:\SweetYaya\MyProj01> django-admin startapp MyApp
同步数据库
E:\SweetYaya\MyProj01> python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
...
Applying sessions.0001_initial... OK
执行如下命令后测试访问 http://127.0.0.1:8000/
E:\SweetYaya\MyProj01>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
June 07, 2021 - 21:16:57
Django version 3.2.4, using settings 'MyProj01.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
2. 自定义User表
打开 MyApp/models.py
文件,创建继承自 AbstractUser
的 UserProfile
类,给它添加 name
和 mobile
字段,它就是我们自定义的用户表。
from django.db import models
from django.contrib.auth.models import AbstractUser
class UserProfile(AbstractUser):
name = models.CharField(max_length=30, null=True, blank=True, verbose_name="姓名")
mobile = models.CharField(max_length=11, verbose_name="电话")
class Meta:
verbose_name = "用户"
verbose_name_plural = "用户"
def __str__(self):
return self.name
3. 序列化和路由
我们直接在 MyProj01/url.py
中进行定义序列化方法和路由配置
from django.urls import path, include
from MyApp.models import UserProfile
from rest_framework import routers, serializers, viewsets
# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = UserProfile
fields = ['url', 'username', 'name', 'mobile', 'email', 'is_staff']
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
queryset = UserProfile.objects.all()
serializer_class = UserSerializer
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register('users', UserViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
3. DRF配置
找到 MyProj01/settings.py
,做如下配置
加入上面创建的应用和 rest_framework
INSTALLED_APPS = [
'django.contrib.admin',
...
'rest_framework',
'MyApp',
]
添加全局认证设置
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated'
]
}
修改默认用户表,至此 settings.py
全部配置完成了。
AUTH_USER_MODEL = 'MyApp.UserProfile'
4. 同步数据库
执行 makemigrations
命令
E:\SweetYaya\MyProj01> python manage.py makemigrations
Migrations for 'MyApp':
MyApp\migrations\0001_initial.py
- Create model UserProfile
执行 migrate
命令出现如下错误
E:\SweetYaya\MyProj01> python manage.py migrate
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "D:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "D:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "D:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "D:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "D:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "D:\Program Files\Python36\lib\site-packages\django\core\management\commands\migrate.py", line 95, in handle
executor.loader.check_consistent_history(connection)
File "D:\Program Files\Python36\lib\site-packages\django\db\migrations\loader.py", line 310, in check_consistent_history
connection.alias,
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency MyApp.0001_initial on database 'default'.
解决办法
先 makemigrations
打开 settings.py
,注释掉 INSTALL_APPS 中的'django.contrib.admin',
打开 urls.py
,注释掉 urlpatterns 中的 admin,再 migrate
就不报错了。最后注意把注释内容恢复回来就好了。
E:\SweetYaya\MyProj01> python manage.py migrate
Operations to perform:
Apply all migrations: MyApp, admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying contenttypes.0002_remove_content_type_name... OK
...
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying sessions.0001_initial... OK
5. 测试
执行命令
E:\SweetYaya\MyProj01>python manage.py runserver
访问 http://127.0.0.1:8000/users/
出现结果如下,此时表明配置成功,但是尚未进行用户登录无权访问。
6. 命令行注册用户
进入 Python Shell
E:\SweetYaya\MyProj01> python manage.py shell
Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 27 2018, 03:37:03) [MSC v.1900 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 6.5.0 -- An enhanced Interactive Python. Type '?' for help.
键入如下代码
In [1]: from MyApp.models import UserProfile
In [2]: from django.contrib.auth.hashers import make_password
In [3]: ist = UserProfile(username='guest01',password=make_password('123456'))
In [4]: ist.save()
In [5]: ist = UserProfile(username='guest02',password=make_password('123456'))
In [6]: ist.save()
然后在数据库中查看 MyApp_userprofile
表发现多了两条记录,添加成功,继续访问 http://127.0.0.1:8000/users/
地址,使用用户密码登录可见如下。测试完成。
来源:https://blog.csdn.net/ShyLoneGirl/article/details/117674422


猜你喜欢
- 由于最近需要做项目,需要进行分词等,查了资料之后,发现python NLTK很强大,于是就想试试看。在网上找了很多安装资料,都不太完整,下载
- 今天给大家分享一下最新版阿里大于的短信验证码在node koa2的实现,还是有很多坑需要注意。首先需要在阿里云注册账号,并获取阿里云访问秘钥
- eg:如在后台的标签列表中,实现上移、下移、置顶功能主要实现思路是节点操作,比如说:上移,直接把点击项移动到前一个节点,以此类推,当然实际代
- PHP页面中如果不希望出现以下情况: 单引号被转义为 \' 双引号被转义为 \" 那么可以进行如下设置以防止: 方法一:在
- QWidget基本介绍基础窗口控件QWidget类是所有用户界面对象的基类,所有的窗口或者控件都直接或者间接的继承自QWidget类。窗口坐
- 一、MySQL 存储过程参数(in) MySQL 存储过程 “in” 参数:跟 C 语言的函数参数的值传递类似, MySQL 存储过程内部可
- 不知道大家有没有一种感觉,每次当使用numpy数组的时候坐标轴总是傻傻分不清楚,然后就会十分的困惑,每次运算都需要去尝试好久才能得出想要的结
- 改编自详解利用OpenCV提取图像中的矩形区域(PPT屏幕等) 原文是c++版,我改成了python版,供大家参考学习。主要思想:边缘检测—
- 配置类config_file:from configparser import ConfigParserclass config_file:
- Jquery练习表单验证 <body> <form action="" method="po
- 网络安全问题很重要,尤其是保证数据安全,遇到很多在写接口的程序员直接都是明文数据传输,在我看来这是很不专业的。本人提倡经过接口的数据都要进行
- 名称空间名称空间(namespaces):用于存放名字与内存地址绑定关系的地方,是对栈区的划分作用:名称空间可以使栈区中存放相同的名字,从而
- 前言:最近工作上遇到个问题,项目开发过程中,开发代码可以通过svn来版本控制,但数据库又该如何来管理呢?多个人接触数据库,当对表、字段或数据
- 介绍在操作数据帧时,初学者有时甚至是更高级的数据科学家会对如何在pandas中使用inplace参数感到困惑。更有趣的是,我看到的解释这个概
- 三角形是个好东西,比如知道三条边边长,可以判断能不能组成三角形(两边之和大于第三边),如果可以就进一步计算其面积(海伦公式),最后还能把这个
- urllib 是 python 的内置模块, 主要用于处理url相关的一些操作,例如访问url、解析url等操作。urllib 包下面的 r
- 本文实例为大家分享了python实现多人聊天室的具体代码,供大家参考,具体内容如下刚开始学习python,写了一个聊天室练练手。Server
- 为了让大家更好的对python中WSGI有更好的理解,我们先从最简单的认识WSGI着手,然后介绍一下WSGI几个经常使用到的接口,了解基本的
- 本文使用案例是基于 python2.7 实现以下内容均为个人使用 peewee 的经验和遇到的坑,不会涉及过多的基本操作。所以,没有使用过
- 在某些情况下,比如自动补全(auto complete)的输入框中,需要使用keyup事件来监听键盘的输入以迅速作出回应。关键在于keyup