创建python环境
conda create -n annotation python=3.6
source activate annotation
conda install Django==2.2.5
pip install djangorestframework
pip install markdown
pip install Pillow
创建工程
mkdir django-drf-react-quickstart
cd django-drf-react-quickstart
django-admin startproject drf_react . # 创建工程
django-admin startapp leads # 创建app
- 打开 ./drf_react/settings.py ,并将新增的app放在 INSTALLED_APPS中:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'leads', # 新增leads app
]
- 打开 ./leads/models.py然後建立Lead model:
class Lead(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
message = models.CharField(max_length=300)
created_at = models.DateTimeField(auto_now_add=True)
- 安装数据库
略....
- 安装数据库的django驱动程序
conda install psycopg2 # postgre
install mysqlclient # mysql
pip install pymysql
- 打开 ./drf_react/settings.py ,并设置数据库配置
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'drf_react',
'USER': 'root',
'PASSWORD': '密碼',
'HOST':'127.0.0.1'
}
- 打开 ./drf_react/settings.py ,并设置本地化
# 語言改為中文
LANGUAGE_CODE = 'zh-hans'
# 時區改為上海
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
# 資料庫儲存使用時間,True時間會被存為UTC的時間
USE_TZ = False
同步数据库
python manage.py makemigrations leads
python manage.py migrate
序列化
- 建立一個新檔案: ./leads/serializers.py.
from rest_framework import serializers
from leads.models import Lead
class LeadSerializer(serializers.ModelSerializer):
class Meta:
model = Lead
fields = ('id', 'name', 'email', 'message') # fields = '__all__'
建立视图
# ./leads/views.py
from leads.models import Lead
from leads.serializers import LeadSerializer
from rest_framework import generics
class LeadListCreate(generics.ListCreateAPIView):
queryset = Lead.objects.all()
serializer_class = LeadSerializer
建立URL映射
# ./drf_react/urls.py
from django.urls import path, include
urlpatterns = [
path('', include('leads.urls')),
]
./drf_react/leads/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('api/lead/', views.LeadListCreate.as_view() ),
]
注册rest_framework
# ./drf_react/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'leads',
'rest_framework' # 加入 rest framework
]
建立实验数据
- 建立资料文件夹
mkdir ./leads/fixtures
gedit ./leads/fixtures/leads.json
# 复制并填写内容如下:
# ./leads/fixtures/leads.json
[
{
"model": "leads.lead",
"pk": 1,
"fields": {
"name": "mtianyan",
"email": "1147727180@qq.com",
"message": "I am a happy pythoner",
"created_at": "2019-01-07 00:00:00"
}
},
{
"model": "leads.lead",
"pk": 2,
"fields": {
"name": "Tom",
"email": "tomsomething@gmail.com",
"message": "I want to talk about a Python project",
"created_at": "2018-01-14 00:00:00"
}
}
]
- 载入数据
# 程序为自动查询要填充数据库的数据
python manage.py loaddata leads
- 预览效果
python manage.py runserver
http://127.0.0.1:8000/api/lead/
安装xadmin后台
- 下载源码,放入工程目录中
mkdir ./extract_apps
git clone -b django2 https://github.com/sshwsfc/xadmin.git ./extract_apps
pip install -r ./extract_apps/requirements.txt
pip install -r ./extract_apps/xadmin/requirements.txt
- 注册app
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'leads', # 新增leads app
'rest_framework', # 新增rest framework
'xadmin', # 新增 xadmin
'crispy_forms', # 新增 xadmin
]
- 注册urls
# django-drf-react-quickstart\drf_react\urls.py
from django.urls import path, include
import xadmin
urlpatterns = [
path('', include('leads.urls')),
path('xadmin/', xadmin.site.urls),
]
- 创建应用app对应的admin
gedit ./leads/adminx.py # 创建新文件
# ./leads/adminx.py
import xadmin
from xadmin import views
from .models import Lead
class BaseSetting(object):
"""xadmin的基礎資訊配置"""
enable_themes = True # 開啟主題功能
use_bootswatch = True
class GlobalSettings(object):
"""xadmin通用資訊配置"""
site_title = "Leads Xadmin"
site_footer = "mtianyan@qq.com"
# 註冊設定資訊到View
xadmin.site.register(views.BaseAdminView, BaseSetting)
xadmin.site.register(views.CommAdminView, GlobalSettings)
class LeadAdmin(object):
"""
list_display: 後臺展示哪些欄位
search_fields: 後臺可搜尋哪些欄位
list_filter: 後臺過濾器可使用哪些欄位
"""
list_display = ['name', 'email','message']
search_fields = ['name', 'email','message']
list_filter = ['name', 'email','message','created_at']
xadmin.site.register(Lead, LeadAdmin)
- 同步数据库
python manage.py makemigrations
python manage.py migrate
- 创建超级管理员
python manage.py createsuperuser
帐号:admin
密码:admin
在线API文档
- 安装软件包
pip install coreapi
- 配置url
# django-drf-react-quickstart\drf_react\urls.py
from django.urls import path, include
import xadmin
from rest_framework.documentation import include_docs_urls # new
urlpatterns = [
path('', include('leads.urls')),
path('xadmin/', xadmin.site.urls),
path('api/docs/', include_docs_urls(title='Lead 线上API文件')), # new
]
- 配置model
# django-drf-react-quickstart\drf_react\models.py
from django.db import models
# Create your models here.
class Lead(models.Model):
name = models.CharField(max_length=100,verbose_name="lead名字", help_text="lead名字")
email = models.EmailField(verbose_name="郵箱", help_text="郵箱")
message = models.CharField(max_length=300, verbose_name="資訊", help_text="資訊")
created_at = models.DateTimeField(auto_now_add=True,verbose_name="建立時間", help_text="建立時間")
参考文献
https://www.cnblogs.com/lyq-biu/p/9513888.html
常见错误
- AutoSchema' object has no attribute 'get_link'
解决方案:在setting.py中添加如下代码
REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' }
网友评论