提示:阅读本章之前,请先阅读目录
django-admin startproject 项目名称
修改
ALLOWED_HOSTS = ["*"]
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_test',
'USER': 'root',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': 3308
}
}
新增
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATICFIELS_DIRS = [
os.path.join(BASE_DIR, "staticfiles")
]
python manage.py runserver
python .\manage.py makemigrations
python .\manage.py migrate
python .\manage.py createsuperuser
用户名 (leave blank to use 'xxxx'): smobee
电子邮件地址: xxxx@qq.com
Password:
Password (again):
密码长度太短。密码必须包含至少 8 个字符。
这个密码太常见了。
密码只包含数字。
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
http://127.0.0.1:8000/admin
依赖requirements.txt
asgiref==3.2.7
certifi==2020.4.5.1
chardet==3.0.4
coreapi==2.3.3
coreschema==0.0.4
Django==3.0.6
django-filter==2.2.0
djangorestframework==3.11.0
idna==2.9
importlib-metadata==1.6.0
itypes==1.2.0
Jinja2==2.11.2
Markdown==3.2.2
MarkupSafe==1.1.1
Pygments==2.6.1
pytz==2020.1
requests==2.23.0
sqlparse==0.3.1
uritemplate==3.0.1
urllib3==1.25.9
zipp==3.1.0
官网
https://www.django-rest-framework.org/#installation
pip install djangorestframework
pip install markdown # Markdown support for the browsable API.
pip install django-filter # Filtering support
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework.authtoken',
]
REST_FRAMEWORK = {
# 分页器
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
# 分页
'PAGE_SIZE': 50,
# 返回的时间格式
'DATETIME_FORMAT': '%Y-%m-%d %H:%M:%S',
# 返回的数据格式
'DEFAULT_RENDER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
],
# 解析request.data
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser',
],
# 全局权限
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated'
],
# 认证方式
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
]
}
python .\manage.py makemigrations
python .\manage.py migrate
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('api-auth/', include('rest_framework.urls')),
path('admin/', admin.site.urls),
]
http://127.0.0.1:8000/api-auth/login/
python .\manage.py startapp course
class CourseConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'course'
verbose_name = '课程信息'
from django.conf import settings
from django.db import models
class Course(models.Model):
name = models.CharField(max_length=255, unique=True, help_text='课程名称', verbose_name='课程名称')
introduction = models.TextField(help_text='课程介绍', verbose_name='课程介绍')
price = models.DecimalField(max_digits=10, decimal_places=2, help_text='课程价格', verbose_name='课程价格')
teacher = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, help_text='课程讲师',
verbose_name='课程讲师')
create_at = models.DateTimeField(auto_now_add=True, help_text='创建时间', verbose_name='创建时间')
update_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
class Meta:
verbose_name = '课程信息'
verbose_name_plural = '课程信息'
ordering = ('price',)
def __str__(self):
return self.name
from django.contrib import admin
from .models import Course
@admin.register(Course)
class CourseAdmin(admin.ModelAdmin):
# 显示哪些字段
list_display = ('name', 'introduction', 'teacher', 'price', 'create_at')
# 搜索字段
search_fields = list_display
# 筛选字段
list_filter = list_display
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'course'
]
python .\manage.py makemigrations
python .\manage.py migrate
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Author : zhongshaofeng
# File : serializers.py
# Time : 2023/6/30 0:06
from django.contrib.auth.models import User
from .models import Course
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
# 序列号所有字段,如果要序列化某些字段,写成元祖即可,('id', 'name', )
fields = '__all__'
class CourseSerializer(serializers.ModelSerializer):
# 引入外键
teacher = serializers.ReadOnlyField(source='teacher.username')
class Meta:
model = Course
fields = '__all__'
# 设置深度
depth = 2
# 带超链接的
# class CourseSerializer(serializers.HyperlinkedModelSerializer):
# # 引入外键
# teacher = serializers.ReadOnlyField(source='teacher.username')
#
# class Meta:
# model = Course
# fields = '__all__'
import json
from django.shortcuts import render
from django.http import HttpRequest, JsonResponse, HttpResponse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from .models import Course
course_dict = {
'name': '数学',
'introduction': '这是一门数学哦',
'price': 256.01
}
@csrf_exempt
def course_list(request: HttpRequest):
"""
Django FBV 原生接口
:param request:
:return:
"""
if request.method == 'GET':
# 查询所有课程
courses = Course.objects.all().values()
# 等同于这种返回
# return HttpResponse(json.dumps(courses), content_type='application/json')
return JsonResponse(list(courses))
if request.method == 'POST':
# post的话,需要引入取消csrf认证
# 序列化
course = json.loads(request.body.decode('utf-8'))
# return HttpResponse(json.dumps(course), content_type='application/json')
return JsonResponse(course, safe=False)
# 这里的name='dispatch',是因为django路由进来时,先走的dispatch
@method_decorator(csrf_exempt, name='dispatch')
class CourseList(View):
"""
Django 的 CBV 编写接口
"""
def get(self, request: HttpRequest):
return JsonResponse(course_dict)
def post(self, request: HttpRequest):
course = json.loads(request.body.decode('utf-8'))
return HttpResponse(json.dumps(course), content_type='application/json')
@api_view(['GET', 'POST'])
def course_function_api(request: HttpRequest):
"""
REST framework 的函数式编写接口
:param request:
:return:
"""
if request.method == 'GET':
s = CourseSerializer(instance=Course.objects.all(), many=True)
return Response(data=s.data, status=status.HTTP_200_OK)
elif request.method == 'POST':
s = CourseSerializer(data=request.data)
if s.is_valid():
s.save(teacher=request.user)
return Response(data=s.data, status=status.HTTP_200_OK)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', 'PUT', 'DELETE'])
def course_detail(request: HttpRequest, pk):
"""
课程操作详情
:param request:
:return:
"""
try:
course = Course.objects.get(pk=pk)
except Course.DoesNotExist:
return Response(data={"msg": "查无此数据"}, status=status.HTTP_400_BAD_REQUEST)
else:
if request.method == 'GET':
s = CourseSerializer(instance=course)
return Response(data=s.data, status=status.HTTP_200_OK)
elif request.method == 'PUT':
s = CourseSerializer(instance=course, data=request.data)
if s.is_valid():
s.save()
return Response(data=s.data, status=status.HTTP_200_OK)
else:
return Response(data={"msg": "该数据无效,无法修改,失败原因:%s" % s.errors}, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
course.delete()
return Response(data={"msg": "删除成功"}, status=status.HTTP_200_OK)
class CourseTwoList(APIView):
"""
类视图的接口
"""
def get_obj(self):
"""
这里写一个通用获取数据
:return:
"""
pass
def get(self):
pass
def post(self):
pass
def delete(self):
pass
class GCourseList(generics.ListCreateAPIView):
"""
通用类视图
"""
queryset = Course.objects.all()
serializer_class = CourseSerializer
def perform_create(self, serializer):
serializer.save(teacher=self.request.user)
class GCourseDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Course.objects.all()
serializer_class = CourseSerializer
class CourseViewSet(viewsets.ModelViewSet):
queryset = Course.objects.all()
serializer_class = CourseSerializer
def perform_create(self, serializer):
serializer.save(teacher=self.request.user)
from django.urls import path, include
from .views import course_list, course_function_api, course_detail, GCourseList, GCourseDetail, CourseViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(prefix="viewsets", viewset=CourseViewSet)
urlpatterns = [
path('list', course_list),
path('function/api', course_function_api),
path('detail/' , course_detail),
path('gcbv/list', GCourseList.as_view()),
path('gcbv/detail/' , GCourseDetail.as_view()),
path('viewsets', CourseViewSet.as_view(
{"get": "list", "post": "create"}
)),
path('viewsets/' , CourseViewSet.as_view(
{"get": "retrieve", "put": "update", "patch": "partial_update"}
)),
path('', include(router.urls))
]
settings.py
安装插件,coreapi
urls.py 引入路由