最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Django rest framework如何自定義用戶表

 更新時(shí)間:2021年06月09日 09:52:17   作者:小龍狗  
Django 默認(rèn)的用戶表很多時(shí)候這些基本字段不夠用,本文介紹在 DRF上使用自定義用戶表進(jìn)行接口訪問控制的功能設(shè)計(jì)。感興趣的可以了解一下

說明

Django 默認(rèn)的用戶表 auth_user 包含 id, password, last_login, is_superuser, username, last_name, email, is_staff, is_active, date_joined, first_name 字段。這些基本字段不夠用時(shí),在此基本表上拓展字段是很好選擇。本文介紹在 DRF(Django Rest Framework) 上使用自定義用戶表進(jìn)行接口訪問控制的功能設(shè)計(jì)。

1. Django項(xiàng)目和應(yīng)用創(chuàng)建

先裝必要的模塊

pip install django
pip install djangorestframework

創(chuàng)建項(xiàng)目文件夾、項(xiàng)目和應(yīng)用

E:\SweetYaya> mkdir MyProj01
E:\SweetYaya> cd MyProj01
E:\SweetYaya\MyProj01> django-admin startproject MyProj01 .
E:\SweetYaya\MyProj01> django-admin startapp MyApp

同步數(shù)據(jù)庫

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

執(zhí)行如下命令后測(cè)試訪問 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 文件,創(chuàng)建繼承自 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 中進(jìn)行定義序列化方法和路由配置

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 ,做如下配置

加入上面創(chuàng)建的應(yīng)用和 rest_framework

INSTALLED_APPS = [
    'django.contrib.admin',
	...
    'rest_framework',
    'MyApp',
]

添加全局認(rèn)證設(shè)置

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated'
    ]
}

修改默認(rèn)用戶表,至此 settings.py 全部配置完成了。

AUTH_USER_MODEL = 'MyApp.UserProfile'

4. 同步數(shù)據(jù)庫

執(zhí)行 makemigrations 命令

E:\SweetYaya\MyProj01> python manage.py makemigrations
Migrations for 'MyApp':
  MyApp\migrations\0001_initial.py
    - Create model UserProfile

執(zhí)行 migrate 命令出現(xiàn)如下錯(cuò)誤

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 就不報(bào)錯(cuò)了。最后注意把注釋內(nèi)容恢復(fù)回來就好了。

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. 測(cè)試

執(zhí)行命令

E:\SweetYaya\MyProj01>python manage.py runserver

訪問 http://127.0.0.1:8000/users/ 出現(xiàn)結(jié)果如下,此時(shí)表明配置成功,但是尚未進(jìn)行用戶登錄無權(quán)訪問。

在這里插入圖片描述

6. 命令行注冊(cè)用戶

進(jìn)入 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()

然后在數(shù)據(jù)庫中查看 MyApp_userprofile 表發(fā)現(xiàn)多了兩條記錄,添加成功,繼續(xù)訪問 http://127.0.0.1:8000/users/ 地址,使用用戶密碼登錄可見如下。測(cè)試完成。

在這里插入圖片描述

到此這篇關(guān)于Django rest framework如何自定義用戶表的文章就介紹到這了,更多相關(guān)Django rest framework自定義用戶表內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 使用Python三角函數(shù)公式計(jì)算三角形的夾角案例

    使用Python三角函數(shù)公式計(jì)算三角形的夾角案例

    這篇文章主要介紹了使用Python三角函數(shù)公式計(jì)算三角形的夾角案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • python3爬蟲之設(shè)計(jì)簽名小程序

    python3爬蟲之設(shè)計(jì)簽名小程序

    這篇文章主要為大家詳細(xì)介紹了python3爬蟲之寫為朋友設(shè)計(jì)簽名的小程序,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-06-06
  • pandas 自定義列名的實(shí)現(xiàn)

    pandas 自定義列名的實(shí)現(xiàn)

    在pandas中,你可以通過多種方法自定義DataFrame的列名,下面就來介紹一下,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-12-12
  • 基于Django的樂觀鎖與悲觀鎖解決訂單并發(fā)問題詳解

    基于Django的樂觀鎖與悲觀鎖解決訂單并發(fā)問題詳解

    這篇文章主要介紹了基于Django的樂觀鎖與悲觀鎖解決訂單并發(fā)問題詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07
  • 基于python pygame實(shí)現(xiàn)的兔子吃月餅小游戲

    基于python pygame實(shí)現(xiàn)的兔子吃月餅小游戲

    pygame是用來開發(fā)游戲的一套基于SDL的模板,它可以是python創(chuàng)建完全界面化的游戲和多媒體程序,而且它基本上可以在任何系統(tǒng)上運(yùn)行,這篇文章主要給大家介紹了基于python pygame實(shí)現(xiàn)的兔子吃月餅小游戲的相關(guān)資料,需要的朋友可以參考下
    2021-09-09
  • Python 3.10 中 6 個(gè)興奮的新特性

    Python 3.10 中 6 個(gè)興奮的新特性

    Python 是當(dāng)今最流行的編程語言之一其流行的原因有很多種,Python 3.10 有幾個(gè)新的很酷的功能,使得使用 Python 成為一種更好的體驗(yàn)。在本文中,我將與您分享 6 個(gè)讓我最興奮的新特性,感興趣的朋友一起看看吧
    2021-10-10
  • GitHub?AI編程工具copilot在Pycharm的應(yīng)用

    GitHub?AI編程工具copilot在Pycharm的應(yīng)用

    最近聽說github出了一種最新的插件叫做copilot,這篇文章主要給大家介紹了關(guān)于GitHub?AI編程工具copilot在Pycharm的應(yīng)用,目前感覺確實(shí)不錯(cuò),建議大家也去使用,需要的朋友可以參考下
    2022-04-04
  • python 圖像判斷,清晰度(明暗),彩色與黑白實(shí)例

    python 圖像判斷,清晰度(明暗),彩色與黑白實(shí)例

    這篇文章主要介紹了python 圖像判斷,清晰度(明暗),彩色與黑白實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • Python操作word常見方法示例【win32com與docx模塊】

    Python操作word常見方法示例【win32com與docx模塊】

    這篇文章主要介紹了Python操作word常見方法,結(jié)合實(shí)例形式分析了Python使用win32com模塊與docx模塊操作word的相關(guān)實(shí)現(xiàn)技巧及相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2018-07-07
  • 讓Python代碼運(yùn)行更快的9個(gè)小技巧

    讓Python代碼運(yùn)行更快的9個(gè)小技巧

    我們經(jīng)常聽到 “Python 太慢了”,“Python 性能不行”這樣的觀點(diǎn),但是,只要掌握一些編程技巧,就能大幅提升 Python 的運(yùn)行速度,今天就讓我們一起來看下讓 Python 性能更高的 9 個(gè)小技巧,需要的朋友可以參考下
    2024-01-01

最新評(píng)論

邛崃市| 朝阳区| 银川市| 承德县| 克东县| 中宁县| 英德市| 静乐县| 青冈县| 高雄市| 黑龙江省| 滨州市| 当阳市| 湛江市| 库尔勒市| 纳雍县| 马关县| 和硕县| 天水市| 新疆| 贵溪市| 曲松县| 区。| 大新县| 内黄县| 花莲市| 云龙县| 修武县| 沁阳市| 宁明县| 怀宁县| 沧源| 大庆市| 兰溪市| 凤台县| 会泽县| 台山市| 秭归县| 广南县| 望都县| 镇平县|