虚拟环境新建项目 rest framework
新建文件夹
mkdir project1
cd project1
新建虚拟环境
virtualenv --no-site-packages env1
cd到project1的bin里 激活虚拟环境 source activate 在虚拟环境中安装依赖 pip install django==1.11.11 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install djangorestframework
序列化
serializers只做一件事情,json化model对象
首先在app01创建一个serializers.py来编写序列化相关的代码:
from app01.models import Comment,Article,School from rest_framework import serializers from rest_framework.validators import ValidationError class CommentSerializer(serializers.ModelSerializer):
#相当于form组件的勾子 def validate_content(self,value): if '草' in value: raise ValidationError('不符合社会主义核心价值观') else: return value class Meta: model = Comment fields = '__all__',所有字段 extra_kwargs = { 'content':{ 'error_message':{ 'required':'内容不能为空', } } } class ArticleModelSerializer(serializers.ModelSerializer): class Meta: model = Article fields = '__all__' #HyperlinkedModelSerializer:建立超链接关系 class ArticleHyperLinkedSerializer(serializers.HyperlinkedModelSerializer): school = serializers.HyperlinkedModelSerializer(view_name='school_detail1111', lookup_url_kwarg='id') class Meta: model = Article fields = {'id','title','type','school'} class SchoolSerializer(serializers.ModelSerializer): class Meta: model = School fields = '__all__'
编写视图文件views.py
from django.shortcuts import render,HttpResponse from django.http import JsonResponse from app01 import models from django import views from rest_framework import serializers from rest_framework.views import APIView from rest_framework.response import Response from app01 import serializers as app01_serializers # Create your views here. class Comment(APIView): def get(self,request): res = {'code':0} # 数据 all_comment = models.Comment.objects.all() #序列化 ser_obj = app01_serializers.CommentSerializer(all_comment,many=True) res['data'] = ser_obj.data return Response(res) def post(self,request): res = {'code':0} # 去提交的数据 comment_data = self.request.data # 对用户提交的数据做校验 ser_obj = app01_serializers.CommentSerializer(data=comment_data) if ser_obj.is_valid(): ser_obj.save() # 表示数据没问题可以创建 else: # 表示数据有问题 res['code'] = 1 res['error'] = ser_obj.errors return HttpResponse('创建新评论') def put(self,request): # rest framework封装好的request print(self,request) print(self.request.data) return HttpResponse('修改评论') def delete(self,request): print(self.request) print(self.request.data) return HttpResponse('删除评论') # 文章CBV class Article(APIView): def get(self,request): res = {'code':0} all_article = models.Article.objects.all() ser_obj = app01_serializers.ArticleHyperLinkedSerializer( all_article,many=True,context={'request':request} ) res['data'] = ser_obj.data return Response(res) def post(self,request): res = {'code':0} ser_obj = app01_serializers.ArticleHyperLinkedSerializer( data=self.request.data) if ser_obj.is_valid(): ser_obj.save() else: res['code'] = 1 res['error']=ser_obj.errors return Response(res) class ArticleDetail(APIView): def get(self,request,pk): res = {'code':0} article_obj = models.Article.objects.filter(pk=pk).first() # 序列化 ser_obj = app01_serializers.ArticleHyperLinkedSerializer(article_obj,context={'request':request}) res['data']=ser_obj.data return Response(res) class SchoolDetail(APIView): def get(self,request,id): res = {'code':0} school_obj = models.School.objects.filter(pk=id).first() ser_obj = app01_serializers.SchoolSerializer(school_obj,context={'request':request}) res['data'] = ser_obj.data return Response(res)
app01/urls.py
from django.conf.urls import url from app01 import views urlpatterns = [ url(r'article/', views.Article.as_view()), url(r'article/(?P<pk>\d+)', views.ArticleDetail.as_view(), name='article-detail'), url(r'school/(?P<id>\d+)', views.SchoolDetail.as_view(), name='school-detail111'), # 评论 # url(r'comment_list/', ), # url(r'add_comment/', ), # url(r'delete_comment/', ), # url(r'edit_comment/', ), url(r'comment/', views.Comment.as_view()), ]
settings.py
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01.apps.App01Config', 'rest_framework' ]