亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術(shù)文章
文章詳情頁

Django rest framework如何自定義用戶表

瀏覽:5日期:2024-09-04 15:25:51
目錄說明1. Django項目和應(yīng)用創(chuàng)建2. 自定義User表3. 序列化和路由3. DRF配置4. 同步數(shù)據(jù)庫5. 測試6. 命令行注冊用戶說明

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

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

先裝必要的模塊

pip install djangopip install djangorestframework

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

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

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

E:SweetYayaMyProj01> python manage.py migrateOperations to perform: Apply all migrations: admin, auth, contenttypes, sessionsRunning 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í)行如下命令后測試訪問 http://127.0.0.1:8000/

E:SweetYayaMyProj01>python manage.py runserverWatching for file changes with StatReloaderPerforming system checks...System check identified no issues (0 silenced).June 07, 2021 - 21:16:57Django 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)建繼承自 AbstractUser 的 UserProfile 類,給它添加 name 和 mobile 字段,它就是我們自定義的用戶表。

from django.db import modelsfrom django.contrib.auth.models import AbstractUserclass 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.name3. 序列化和路由

我們直接在 MyProj01/url.py 中進(jìn)行定義序列化方法和路由配置

from django.urls import path, includefrom MyApp.models import UserProfilefrom rest_framework import routers, serializers, viewsets# Serializers define the API representation.class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta:model = UserProfilefields = [’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:SweetYayaMyProj01> python manage.py makemigrationsMigrations for ’MyApp’: MyAppmigrations0001_initial.py - Create model UserProfile

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

E:SweetYayaMyProj01> python manage.py migrateTraceback (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 FilesPython36libsite-packagesdjangocoremanagement__init__.py', line 419, in execute_from_command_line utility.execute() File 'D:Program FilesPython36libsite-packagesdjangocoremanagement__init__.py', line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File 'D:Program FilesPython36libsite-packagesdjangocoremanagementbase.py', line 354, in run_from_argv self.execute(*args, **cmd_options) File 'D:Program FilesPython36libsite-packagesdjangocoremanagementbase.py', line 398, in execute output = self.handle(*args, **options) File 'D:Program FilesPython36libsite-packagesdjangocoremanagementbase.py', line 89, in wrapped res = handle_func(*args, **kwargs) File 'D:Program FilesPython36libsite-packagesdjangocoremanagementcommandsmigrate.py', line 95, in handle executor.loader.check_consistent_history(connection) File 'D:Program FilesPython36libsite-packagesdjangodbmigrationsloader.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 就不報錯了。最后注意把注釋內(nèi)容恢復(fù)回來就好了。

E:SweetYayaMyProj01> python manage.py migrateOperations to perform: Apply all migrations: MyApp, admin, auth, contenttypes, sessionsRunning 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... OK5. 測試

執(zhí)行命令

E:SweetYayaMyProj01>python manage.py runserver

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

Django rest framework如何自定義用戶表

6. 命令行注冊用戶

進(jìn)入 Python Shell

E:SweetYayaMyProj01> python manage.py shellPython 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 informationIPython 6.5.0 -- An enhanced Interactive Python. Type ’?’ for help.

鍵入如下代碼

In [1]: from MyApp.models import UserProfileIn [2]: from django.contrib.auth.hashers import make_passwordIn [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/ 地址,使用用戶密碼登錄可見如下。測試完成。

Django rest framework如何自定義用戶表

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

標(biāo)簽: Django
相關(guān)文章:
主站蜘蛛池模板: 亚洲精品一区国产二区 | 日韩黄色三级视频 | 天天在线天天综合网色 | 国产精品乳摇在线播放 | 成人黄网大全在线观看 | 手机看片自拍自自拍日韩免费 | 欧美黄色第一页 | 欧美一区二区三区久久综 | 亚洲欧美日韩另类在线一 | 中文字幕 亚洲一区 | 欧美一区永久视频免费观看 | 一区二区三区在线看 | 国产成人在线免费视频 | 麻豆视频成人 | 最新国产精品好看的国产精品 | 国产精品视频久 | 一区二区三区高清视频在线观看 | 日韩色影视| 亚洲自拍色 | 亚洲国产成人手机在线电影bd | 日韩欧美一区二区三区 | 中日韩视频在线看免费观看 | 91精品日韩 | 日本一区二区不卡在线 | 三级很黄很黄的视频 | 久久久91精品国产一区二区 | 亚洲免费午夜视频 | 人人干视频在线观看 | 国产在视频线精品视频二代 | 色天天综合网色鬼综合 | 国产美女久久久久久久久久久 | 日本黄色性生活片 | 精品免费久久久久久成人影院 | 日本黄色免费大片 | 成人精品视频在线观看播放 | 麻豆视传媒短视频网站链接 | a级毛片在线播放 | 国产中日韩一区二区三区 | 伊人久久婷婷 | 精品欧美亚洲韩国日本久久 | 国产日产欧产麻豆精品精品推荐 |