初学Django基础04 http|jsonresponse,filter模板过滤器,cvb与fvb
django HttpResponse和JsonResponse
from django.http import HttpResponse, JsonResponse # JsonResponse参数传字典,内部对字典进行处理,返回json串 def stu(request): data = {'msg': '处理成功'} return JsonResponse(data, json_dumps_params={"ensure_ascii": False}) #json_dumps_params指定附加参数:给返回数据中文编码 # 而HttpResponse返回字符串 import json def stu1(request): data = {'msg': '处理成功'} return HttpResponse(data, json.dumps(data,ensure_ascii=False)) #json_dumps_params指定附加参数:给返回数据中文编码
django模板filter
filter是django模板中自带的过滤器,当后端不分离时,过滤器能够自定义的处理页面的展示信息,通过格式是以 {{ 变量 | filter模板过滤器:值 }}
# views.py def this_test(request): age = 18 name = 'rainbol' content = 'django有自带的分页,非常的好用,代码如下:django有自带的分页,非常的好用,代码如下:django有自带的分页,非常的好用,代码如下:' navs = ["我的日记", "我的相册", '我的心情', '我的心情1', '我的心情2', '我的心情3'] comments = "<h1 style='color:red'>你好呀</h1>" js_str = "<script>alert('666)</script>" import datetime time = datetime.datetime.now() content2 = "我是谁,我在哪,我要到哪儿去" content3 = "今天是个好日子,程序员心情不错,啦啦啦是sb,笑笑笑是sb,啊啊啊是sb" return render(request, 'test.html', locals()) #locals()返回一口气返回所有变量信息
{% load my_tags %} {#调用自定义html必须写上面的方法#} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>django模板filter</title> </head> <body> {#添加,如果是数字自己计算,如果是字符串自动拼接#} {{ age }} {{ age |add:1 }} {#特别注意k:v之间不能有空格不然会报错 False->{{ age|add : 1 }}#} <br> {#普通后端传给前端数据是字符串,加上safe认为把字符串转换成前端代码,之前是防止js,css注入用的#} {{ comments |safe }} <br> {#truncatechars是django自带的过滤器,截取10个字段,后面的字段以 <..> 表示#} {{ content1 | truncatechars:10 }} <br> {#切片#} {{ navs |slice:":2" }} <br> {#获取长度#} {{ navs |length }} <br> {#拿到第一个字段#} {{ navs.0 }} <br> {#拼接#} {{ navs | join:'--' }} <br> {#所有大写#} {{ name |upper }} <br> {#author没有传,或者为空,显示默认值管理员,如果值就显示那个值#} {{ author|default:"管理员" }} <br> {#按照所指定的时间来设置时间,注意分钟是i #} {{ time|date:'Y-m-d H:i:s' }}
{#一般字节长度,可以通过下面方式转成kb等形式#} <p>{{file_size|filesizeformat}}</p>
{#替换字符串自定义方法(1),后台处理修改的值,如敏感词替换#} {{ content1 |custom_name1 }} <br> {#替换字符串自定义方法(2)该页面处理修改的值#} {{ content2 |custom_name2:'Rain' }} <br> {#支持多个参数#} {% content_value3 content3 "程序员" "sb" %} </body> </html>
# my_tags.py # 自定义filter模板,在子项目创建一个里面带有__init__.py的文件夹,文件夹名称必须叫templatetags,文件夹名称必须叫templatetags下随便起一个py文件即可 from django import template register = template.Library() # 变量必须交register @register.filter(name='custom_name1') # 必须添加装饰器 def content_value1(value): true_value = 'django' if true_value in value: value = value.replace(true_value, 'python') return value # 传参形式,filter最多只能两个参数,参数1为字符串,参数2为要替换的字符串 @register.filter(name='custom_name2') def content_value2(value, s): true_value = '我' if true_value in value: value = value.replace(true_value, s) return value # 传参形式解决多个参数传参问题 @register.simple_tag def content_value3(value, *args): # *args不限参数限制 for s in args: value = value.replace(s, '**') return value
django实现cvb接口
后端接口定义如果是按照传统定义的方法,增,删,改,查,需要定义四个接口来做同一件事情,我们可以通过get(查),post(添加),put(修改),delete(删除)这四个不同的请求方式用一个接口实现
fvb(function views base)
def TestView1(request): if request.GET.get() == 'GET': print('这是get请求') elif request.POST.get() == 'POST': print('这是post请求') else: print('其他请求')
cvb(class views base)
#view.py
from django.views import View
#继承View后,cvb需要指定get,post,put,delete方法,请求会自动执行该方法里面的函数
class TestView2(View): def get(self, request): return JsonResponse({'get': 'ok'}, json_dumps_params={"ensure_ascii": False}) def post(self, request): return JsonResponse({'post': 'ok'}, json_dumps_params={"ensure_ascii": False}) def put(self, request): return JsonResponse({'put': 'ok'}, json_dumps_params={"ensure_ascii": False}) def delete(self, request): return JsonResponse({'del': 'ok'}, json_dumps_params={"ensure_ascii": False})
#url.py urlpatterns = [ path('student', views2.StudentView.as_view() ), #注意类需要调用as_view()方法才能转换成功,而函数不用 ]
cvb后端接口实现增删改查
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import datetime import decimal import json from django.core.paginator import Paginator from django.http import HttpResponse, JsonResponse from django.views import View from .models import Student from django.forms import ModelForm from django.db.models import Q class StudentForm(ModelForm): class Meta: model = Student fields = '__all__' # 代表所有的字段 # fields = ['name','phone'] #某个字段 # exclude = ['status', 'is_delete'] # 排查哪个字段 class MyJSONEncoder(json.JSONEncoder): # 返回显示的json格式处理 def default(self, obj): if isinstance(obj, datetime.datetime): return obj.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(obj, datetime.date): return obj.strftime('%Y-%m-%d') elif isinstance(obj, decimal.Decimal): return float(obj) else: return json.JSONEncoder.default(self, obj) class StudentView(View): search_field = ['name', 'phone', 'Email'] # 存放搜索的字段 filter_field = ['name', 'phone', 'Email'] # 指定过滤条件 ?name=1213&phone=1223432532&Email=2123.com def get(self, request): # QuerySet search = request.GET.get('search') limit = request.GET.get('limit', 20) page = request.GET.get('page', 1) field_dict = {} for field in self.filter_field: # 过滤字段 value = request.GET.get(field, None) if value: field_dict[field] = value q_result = Q() # 定义Q的空字典来存放数据 if search: for field in self.search_field: # 实现模糊查询 d = {'%s__contains' % field: search} q_result = Q(**d) | q_result # 每一次for循环都能把值增加个result中,实现多个字段过滤 all_students = Student.objects.filter(**field_dict).filter(q_result).filter(is_delete=0, status=1).values() # 先过滤再模糊查询 # 实现分页显示查找列表 page_obj = Paginator(all_students, limit) stus = list(page_obj.get_page(page)) data = {"error_code": 0, "msg": "操作成功", "data": stus, "count": page_obj.count} return JsonResponse(data, json_dumps_params={"ensure_ascii": False}, encoder=MyJSONEncoder) # encoder实现自己的时间格式 def post(self, request): stu_form = StudentForm(request.POST) if stu_form.is_valid(): Student.objects.create(**stu_form.cleaned_data) data = {"error_code": 0, 'msg': '添加成功'} else: data = {"error_code": -1, 'msg': stu_form.errors.get_json_data()} return JsonResponse(data, json_dumps_params={"ensure_ascii": False}) def put(self, request): # 如果是PUT请求的话 ,request.POST里面没有PUT的数据,坑! # 解决方法是获取request.Meta原始请求数据 id = request.GET.get('id') if not id: data = {"error_code": -1, 'msg': '修改失败'} else: put_data, file = request.parse_file_upload(request.META, request) # parse_file_upload解析请求元数据 stu_form = StudentForm(put_data) clean_data = {} if stu_form.is_valid(): # 全部传参校验通过 Student.objects.filter(uid=id).update(**stu_form.cleaned_data) # 如果校验通过,自动解包并修改到数据库中 data = {"error_code": 1, 'msg': '修改成功'} else: # 校验部分传参处理 not_pass_data = set(stu_form.errors.get_json_data().keys()) # 拿到没有校验通过的字段 send_data = set(put_data.keys()) if not_pass_data & send_data: # 如果所有字段的key和不通过的key存在交集,这个交集的值就是没有传的字段,否则是传了的字段都已经通过校验了 public_data = not_pass_data - send_data # 拿到差集 stu_data = stu_form.errors.get_json_data() for s in public_data: stu_data.pop(s) data = {"error_code": -1, 'msg': stu_data} else: for k in set(put_data.keys()): clean_data[k] = put_data.get(k) Student.objects.filter(uid=id).update(**clean_data) data = {"error_code": 1, 'msg': '修改成功'} return JsonResponse(data, json_dumps_params={"ensure_ascii": False}) def delete(self, request): id = request.GET.get('id') if id: res = Student.objects.filter(status=1, is_delete=0).filter(uid=id).delete() if res[0]: data = {"error_code": -1, 'msg': '删除成功'} return JsonResponse(data, json_dumps_params={"ensure_ascii": False}) data = {"error_code": -1, 'msg': '删除失败'} return JsonResponse(data, json_dumps_params={"ensure_ascii": False})