1.安装虚拟环境
#mkvirtualenv drfdemo -p python3 #pip install django #pip install djangorestframework #pip install pymysql
2.创建项目
django-admin startproject myuser
3.添加drf应用
在settings.py的INSTALLED_APPS中添加‘rest_framework‘。
INSTALLED_APPS = [ ... ‘rest_framework‘, ]
4.创建数据库
create database myuser;
5.修改项目数据库连接配置
settings.py配置文件中设置mysql的账号密码
DATABASES = { # ‘default‘: { # ‘ENGINE‘: ‘django.db.backends.sqlite3‘, # ‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘), # } ‘default‘: { ‘ENGINE‘: ‘django.db.backends.mysql‘, ‘NAME‘: "myuser", "HOST": "127.0.0.1", "PORT": 3306, "USER": "root", "PASSWORD": "123456", }, }
6.主引用中__init__.py设置使用pymysql作为数据库驱动
import pymysql pymysql.install_as_MySQLdb()
7.修改mysql会遇到的两个问题:
(1)‘mysqlclient 1.3.13 or newer is required; you have %s.‘ % Database.__version__
raise ImproperlyConfigured(‘mysqlclient 1.3.13 or newer is required; you have %s.‘ % Database.__version__)
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.
\lib\site-packages\django\db\backends\mysql\base.py 里面进行注释
(2)query = query.decode(errors=‘replace‘)
AttributeError: ‘str‘ object has no attribute ‘decode‘
backends/mysql/operations.py146行里面新增一个行代码:
query = query.encode()
8.创建app
python manage.py startapp userinfo
9.添加userinfo应用(代码修改为):
INSTALLED_APPS = [ ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘rest_framework‘, ‘userinfo‘, ]
settings添加一条user模型继承的配置:
# 继承模型的认证 AUTH_USER_MODEL = "userinfo.User"
10.编写继承drf原user模型的模型:
代码如下:
from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): # 只添加手机号一个字段 mobile = models.CharField(max_length=100)
11.总路由为:
from django.contrib import admin from django.urls import path,include urlpatterns = [ path(‘admin/‘, admin.site.urls), path(‘user/‘, include("userinfo.urls")),
12.app应用下的路由为:
from rest_framework.routers import DefaultRouter from userinfo import views urlpatterns = [] # 路由列表 router = DefaultRouter() # 可以处理视图的路由器 router.register(‘userinfo‘, views.UserAPIView) # url进行注册 urlpatterns += router.urls # 将路由器中的所有路由信息追加到django的路由列表中 print(urlpatterns)
13.序列化器代码:
from rest_framework import serializers from userinfo.models import User # 创建序列化器类,回头会在视图中被调用 class UserModelSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" def create(self, validated_data): # 调用当前模型序列化器父类的create user = super().create(validated_data) # 对密码进行加密,还可以使用 make_password user.set_password(user.password) user.save() return user
14.视图代码为:
from rest_framework.viewsets import ModelViewSet from userinfo.models import User from userinfo.serializers import UserModelSerializer class UserAPIView(ModelViewSet): queryset = User.objects.all() serializer_class = UserModelSerializer
15.迁移:
python manage.py makemigrations python manage.py migrate
最后成功生成了,继承drf中的原生user模型:
16.进行增删改成测试:
可以使用:
http://127.0.0.1:8000/user/userinfo/
进行新增数据,如下:
可以删除数据(比如id为2的):
http://127.0.0.1:8000/user/userinfo/2/
查询全部:
http://127.0.0.1:8000/user/userinfo/
数据只剩一个(原来添加了id为1,2的两个数据)
更新id为3 的数据:
http://127.0.0.1:8000/user/userinfo/3/
{
"id": 3,
"password": "4142432",
"is_superuser": false,
"username": "three01",
"mobile": "17644551518"
}
最后导出相应的库文件:
# 命令:pip freeze > requirements.txt
Django==2.2.4
djangorestframework==3.10.2
PyMySQL==0.9.3
pytz==2019.2
sqlparse==0.3.0
这样直接继承原生的user模型的demo完成
原文地址:https://www.cnblogs.com/hszstudypy/p/11595889.html