1. Installing the Virtual Environment
#mkvirtualenv drfdemo -p python3 #pip install django #pip install djangorestframework #pip install pymysql
2. Create a project
django-admin startproject myuser
3. Add drf application
In settings.py of INSTALLED_APPS added in 'rest_framework' .
INSTALLED_APPS = [ ... 'rest_framework', ]
4. Create a database
create database myuser;
5. modify the connection configuration item database
settings.py configuration file settings mysql account password
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. The primary references __init__.py provided using pymysql as database-driven
import pymysql pymysql.install_as_MySQLdb()
7. Modify mysql two problems encountered:
(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 inside annotate
(2)query = query.decode(errors='replace')
AttributeError: 'str' object has no attribute 'decode'
backends / mysql / operations.py146 rows inside a new line of code:
query = query.encode()
8. Creating app
python manage.py startapp userinfo
9. Add userinfo application ( code changes to ) :
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'userinfo', ]
settings to add a user model inherited configuration:
# Authentication inheritance model AUTH_USER_MODEL = " userinfo.User "
10. The preparation of inherited drf original user model model:
code show as below:
from django.contrib.auth.models Import AbstractUser from django.db Import Models class the User (AbstractUser): # add only a phone number field Mobile = models.CharField (max_length = 100)
11. The total route is:
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('user/', include("userinfo.urls")),
12.app applications in routing as follows:
from rest_framework.routers Import defaultrouter from UserInfo Import views the urlpatterns = [] # routing list Router = defaultrouter () # can handle the view router router.register ( ' UserInfo ' , views.UserAPIView) # URL registered the urlpatterns + = router.urls # All routing information is appended to the router's routing table django Print (urlpatterns)
13. serialization code:
from rest_framework Import serializers from userinfo.models Import the User # Create serializer class, will be called back in the view class UserModelSerializer (serializers.ModelSerializer): class Meta -: Model = the User Fields = " __all__ is " DEF Create (Self, validated_data) : # call to create a current model serialization is the parent class User = . Super () create (validated_data) # encrypts the password may also be used make_password user.set_password (user.password) user.save () return User
14. The view code:
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. Migration:
python manage.py makemigrations
python manage.py migrate
Finally successfully generated, inheritance drf native of user model:
16. The additions and deletions into a test:
You can use :
http://127.0.0.1:8000/user/userinfo/
New data were as follows:
You can delete data ( such as id for the 2 's ) :
http://127.0.0.1:8000/user/userinfo/2/
All inquiries:
http://127.0.0.1:8000/user/userinfo/
A data only (the original two data id added 1,2)
Update id for the 3 data:
http://127.0.0.1:8000/user/userinfo/3/
{
"id": 3,
"password": "4142432",
"is_superuser": false,
"username": "three01",
"mobile": "17644551518"
}
Finally, export the appropriate library file:
# 命令:pip freeze > requirements.txt
Django==2.2.4
djangorestframework==3.10.2
PyMySQL==0.9.3
pytz==2019.2
sqlparse==0.3.0
Such direct successor to the demo native user model is completed