Django rest framework如何自定义用户表

 更新时间:2021年06月09日 09:52:17   作者:小龙狗  
Django 默认的用户表很多时候这些基本字段不够用,本文介绍在 DRF上使用自定义用户表进行接口访问控制的功能设计。感兴趣的可以了解一下

说明

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

在这里插入图片描述

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自定义用户表内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python中time模块与datetime模块在使用中的不同之处

    Python中time模块与datetime模块在使用中的不同之处

    这篇文章主要介绍了Python中time模块与datetime模块在使用中的不同之处,是Python入门学习中的基础知识,需要的朋友可以参考下
    2015-11-11
  • 通过Python pyecharts输出保存图片代码实例

    通过Python pyecharts输出保存图片代码实例

    这篇文章主要介绍了通过Python pyecharts输出保存图片代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • python pandas dataframe多列筛选方式

    python pandas dataframe多列筛选方式

    这篇文章主要介绍了python pandas dataframe多列筛选方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09
  • pyqt5主窗口按键弹出子窗口的实现

    pyqt5主窗口按键弹出子窗口的实现

    本文主要介绍了pyqt5主窗口按键弹出子窗口的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-02-02
  • Python+radar实现随机日期时间的生成

    Python+radar实现随机日期时间的生成

    Python有广泛丰富的第三方库,在没有特殊定制下,避免了重复造轮子。本文将利用radar库实现生成随机的日期或时间,文中的示例代码讲解详细,感兴趣的可以了解一下
    2022-05-05
  • python实现网页链接提取的方法分享

    python实现网页链接提取的方法分享

    这篇文章主要介绍了python实现的网页链接提取的方法,需要的朋友可以参考下
    2014-02-02
  • Python字符串的常见操作实例小结

    Python字符串的常见操作实例小结

    这篇文章主要介绍了Python字符串的常见操作,结合实例形式总结分析了Python字符串的查询、转换、分割、计算等相关操作技巧,需要的朋友可以参考下
    2019-04-04
  • python实现word/excel/ppt批量转pdf的示例代码

    python实现word/excel/ppt批量转pdf的示例代码

    这篇文章主要为大家详细介绍了如何利用python实现word、excel、ppt批量转pdf文件,文中的示例代码讲解详细,有需要的小伙伴可以参考下
    2023-09-09
  • Python将一个Excel拆分为多个Excel

    Python将一个Excel拆分为多个Excel

    这篇文章主要为大家详细介绍了Python将一个Excel拆分为多个Excel,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-11-11
  • 解读dataframe中有关inf的处理技巧

    解读dataframe中有关inf的处理技巧

    这篇文章主要介绍了解读dataframe中有关inf的处理技巧,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09

最新评论