views.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from json import JSONEncoder
  2. from django import forms
  3. from django.http import JsonResponse
  4. from django.shortcuts import render
  5. from search.models import CarRecord
  6. # 序列化/串行化/腌咸菜 - 把对象按照某种方式处理成字节或者字符的序列
  7. # 反序列化/反串行化 - 把字符或者字节的序列重新还原成对象
  8. # Python实现序列化和反序列化的工具模块 - json / pickle / shelve
  9. # return HttpResponse(json.dumps(obj), content_type='application/json')
  10. # return JsonResponse(obj, encoder=, safe=False)
  11. # from django.core.serializers import serialize
  12. # return HttpResponse(serialize('json', obj), content_type='application/json; charset=utf-8')
  13. class CarRecordEncoder(JSONEncoder):
  14. def default(self, o):
  15. del o.__dict__['_state']
  16. o.__dict__['date'] = o.happen_date
  17. return o.__dict__
  18. def ajax_search(request):
  19. if request.method == 'GET':
  20. return render(request, 'search2.html')
  21. else:
  22. carno = request.POST['carno']
  23. record_list = list(CarRecord.objects.filter(carno__icontains=carno))
  24. # 第一个参数是要转换成JSON格式(序列化)的对象
  25. # encoder参数要指定完成自定义对象序列化的编码器(JSONEncoder的子类型)
  26. # safe参数的值如果为True那么传入的第一个参数只能是字典
  27. # return HttpResponse(json.dumps(record_list), content_type='application/json; charset=utf-8')
  28. return JsonResponse(record_list, encoder=CarRecordEncoder,
  29. safe=False)
  30. def search(request):
  31. # 请求行中的请求命令
  32. # print(request.method)
  33. # 请求行中的路径
  34. # print(request.path)
  35. # 请求头(以HTTP_打头的键是HTTP请求的请求头)
  36. # print(request.META)
  37. # 查询参数: http://host/path/resource?a=b&c=d
  38. # print(request.GET)
  39. # 表单参数
  40. # print(request.POST)
  41. if request.method == 'GET':
  42. ctx = {'show_result': False}
  43. else:
  44. carno = request.POST['carno']
  45. ctx = {
  46. 'show_result': True,
  47. 'record_list': list(CarRecord.objects.filter(carno__contains=carno))}
  48. return render(request, 'search.html', ctx)
  49. class CarRecordForm(forms.Form):
  50. carno = forms.CharField(min_length=7, max_length=7, label='车牌号', error_messages={'carno': '请输入有效的车牌号'})
  51. reason = forms.CharField(max_length=50, label='违章原因')
  52. punish = forms.CharField(max_length=50, required=False, label='处罚方式')
  53. def add(request):
  54. errors = []
  55. if request.method == 'GET':
  56. f = CarRecordForm()
  57. else:
  58. f = CarRecordForm(request.POST)
  59. if f.is_valid():
  60. CarRecord(**f.cleaned_data).save()
  61. f = CarRecordForm()
  62. else:
  63. errors = f.errors.values()
  64. return render(request, 'add.html', {'f': f, 'errors': errors})