Django rest framework如何自定义用户表


Posted in Python onJune 09, 2021

说明

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 文件,创建继承自 AbstractUserUserProfile 类,给它添加 namemobile 字段,它就是我们自定义的用户表。

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/ 出现结果如下,此时表明配置成功,但是尚未进行用户登录无权访问。

Django rest framework如何自定义用户表

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/ 地址,使用用户密码登录可见如下。测试完成。

Django rest framework如何自定义用户表

到此这篇关于Django rest framework如何自定义用户表的文章就介绍到这了,更多相关Django rest framework自定义用户表内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python 提取文件的小程序
Jul 29 Python
python 容器总结整理
Apr 04 Python
Python实现PS滤镜特效Marble Filter玻璃条纹扭曲效果示例
Jan 29 Python
python编辑用户登入界面的实现代码
Jul 16 Python
Python3爬虫学习之应对网站反爬虫机制的方法分析
Dec 12 Python
python将处理好的图像保存到指定目录下的方法
Jan 10 Python
python实现微信每日一句自动发送给喜欢的人
Apr 29 Python
python3 map函数和filter函数详解
Aug 26 Python
python GUI库图形界面开发之PyQt5打开保存对话框QFileDialog详细使用方法与实例
Feb 27 Python
python安装第三方库如xlrd的方法
Oct 31 Python
Python爬虫之Selenium实现键盘事件
Dec 04 Python
用python自动生成日历
Apr 24 Python
如何使用Python提取Chrome浏览器保存的密码
Jun 09 #Python
python缺失值的解决方法总结
Jun 09 #Python
Python提取PDF指定内容并生成新文件
Python激活Anaconda环境变量的详细步骤
Jun 08 #Python
Python序列化与反序列化相关知识总结
Jun 08 #Python
浅谈怎么给Python添加类型标注
Python如何导出导入所有依赖包详解
Jun 08 #Python
You might like
php下将多个数组合并成一个数组的方法与实例代码
2011/02/03 PHP
基于PHP的cURL快速入门教程 (小偷采集程序)
2011/06/02 PHP
浅析php header 跳转
2013/06/17 PHP
php curl获取https页面内容,不直接输出返回结果的设置方法
2019/01/15 PHP
php传值和传引用的区别点总结
2019/11/19 PHP
采用CSS和JS,刚好我最近有个站点要用到下拉菜单!
2006/06/26 Javascript
用js小类库获取浏览器的高度和宽度信息
2012/01/15 Javascript
js window.onload 加载多个函数和追加函数详解
2014/01/08 Javascript
纯js模拟div层弹性运动的方法
2015/07/27 Javascript
基于PHP和Mysql相结合使用jqGrid读取数据并显示
2015/12/02 Javascript
jquery 判断div show的状态实例
2016/12/03 Javascript
node.js中grunt和gulp的区别详解
2017/07/17 Javascript
JS 60秒后重新发送验证码的实例讲解
2017/07/26 Javascript
Vue中render方法的使用详解
2018/01/26 Javascript
vue-quill-editor+plupload富文本编辑器实例详解
2018/10/19 Javascript
Vue实现远程获取路由与页面刷新导致404错误的解决
2019/01/31 Javascript
js作用域和作用域链及预解析
2019/04/11 Javascript
layer 刷新某个页面的实现方法
2019/09/05 Javascript
python通过cookie模拟已登录状态的初步研究
2016/11/09 Python
Python中xrange与yield的用法实例分析
2017/12/26 Python
Windows下Anaconda的安装和简单使用方法
2018/01/04 Python
Python 调用 Outlook 发送邮件过程解析
2019/08/08 Python
Python如何使用k-means方法将列表中相似的句子归类
2019/08/08 Python
python读取Excel表格文件的方法
2019/09/02 Python
python speech模块的使用方法
2020/09/09 Python
HTML5中5个简单实用的API(第二篇,含全屏、可见性、拍照、预加载、电池状态)
2014/05/07 HTML / CSS
HTML5学习心得总结(推荐)
2016/07/08 HTML / CSS
详解webapp页面滚动卡顿的解决办法
2018/12/26 HTML / CSS
英国和国际包裹递送:ParcelCompare
2019/08/26 全球购物
《搭石》教学反思
2014/04/07 职场文书
老人再婚离婚协议书范本
2014/10/27 职场文书
2014年医院工作总结
2014/11/20 职场文书
2015秋季开学典礼主持词
2015/07/16 职场文书
2015年成本会计工作总结
2015/10/14 职场文书
优秀党员主要事迹范文
2015/11/05 职场文书
Z-Order加速Hudi大规模数据集方案分析
2022/03/31 Servers