Skip to content

Commit 70b6b6e

Browse files
committed
更新了Django实例代码
1 parent 52252f5 commit 70b6b6e

File tree

3 files changed

+48
-15
lines changed

3 files changed

+48
-15
lines changed

Day31-Day35/car/search/views.py

+36-10
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1+
from datetime import datetime
12
from json import JSONEncoder
23

34
from django import forms
45
from django.http import JsonResponse
5-
from django.shortcuts import render
6+
from django.shortcuts import render, redirect
67

78
from search.models import CarRecord
89

@@ -13,6 +14,7 @@
1314
# return JsonResponse(obj, encoder=, safe=False)
1415
# from django.core.serializers import serialize
1516
# return HttpResponse(serialize('json', obj), content_type='application/json; charset=utf-8')
17+
MAX_AGE = 14 * 24 * 60 * 60
1618

1719

1820
class CarRecordEncoder(JSONEncoder):
@@ -24,8 +26,22 @@ def default(self, o):
2426

2527

2628
def ajax_search(request):
29+
current_time = datetime.now().ctime()
30+
# Cookie是保存在浏览器临时文件中的用户数据(通常是识别用户身份的ID/token或者是用户的偏好设置)
31+
# 因为每次请求服务器时在HTTP请求的请求头中都会携带本网站的Cookie数据
32+
# 那么服务器就可以获取这些信息来识别用户身份或者了解用户的偏好 这就是所谓的用户跟踪
33+
# 因为HTTP本身是无状态的 所以需要使用Cookie/隐藏域/URL重写这样的技术来实现用户跟踪
34+
# 从请求中读取指定的cookie - 通过cookie的名字找到对应的值
35+
# 如果请求中没有指定名字的cookie可以通过get方法的第二个参数设置一个默认的返回值
36+
last_visit_time = request.COOKIES.get('last_visit_time')
2737
if request.method == 'GET':
28-
return render(request, 'search2.html')
38+
response = render(request, 'search2.html',
39+
{'last': last_visit_time if last_visit_time
40+
else '你是第一次访问我们的网站'})
41+
# 通过render渲染页面后先用set_cookie方法设置cookie后再返回HttpResponse对象
42+
# 第一个参数是cookie的名字 第二个参数是cookie的值 第三个参数是过期时间(秒)
43+
response.set_cookie('last_visit_time', current_time, max_age=MAX_AGE)
44+
return response
2945
else:
3046
carno = request.POST['carno']
3147
record_list = list(CarRecord.objects.filter(carno__icontains=carno))
@@ -58,21 +74,31 @@ def search(request):
5874
return render(request, 'search.html', ctx)
5975

6076

61-
class CarRecordForm(forms.Form):
77+
class CarRecordForm(forms.ModelForm):
6278
carno = forms.CharField(min_length=7, max_length=7, label='车牌号', error_messages={'carno': '请输入有效的车牌号'})
6379
reason = forms.CharField(max_length=50, label='违章原因')
6480
punish = forms.CharField(max_length=50, required=False, label='处罚方式')
6581

82+
"""
83+
# 执行额外的表单数据验证
84+
def clean_carno(self):
85+
_carno = self.cleaned_data['carno']
86+
if not condition:
87+
raise forms.ValidationError('...')
88+
return _carno
89+
"""
90+
91+
class Meta:
92+
model = CarRecord
93+
fields = ('carno', 'reason', 'punish')
94+
6695

6796
def add(request):
68-
errors = []
6997
if request.method == 'GET':
70-
f = CarRecordForm()
98+
f = CarRecordForm(initial={'reason': '打警察', 'punish': '牢底坐穿'})
7199
else:
72100
f = CarRecordForm(request.POST)
73101
if f.is_valid():
74-
CarRecord(**f.cleaned_data).save()
75-
f = CarRecordForm()
76-
else:
77-
errors = f.errors.values()
78-
return render(request, 'add.html', {'f': f, 'errors': errors})
102+
f.save()
103+
return redirect('/search2')
104+
return render(request, 'add.html', {'f': f})

Day31-Day35/car/templates/add.html

+11-5
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,20 @@
1414
<h2>添加违章记录</h2>
1515
<hr>
1616
<p>
17-
{% for err in errors %}
18-
<div class="err">{{ err }}</div>
17+
{% for hint in hints %}
18+
<div class="err">{{ hint }}</div>
1919
{% endfor %}
2020
</p>
2121
<form action="/add" method="post">
22-
<table>
23-
{{ f.as_table }}
24-
</table>
22+
{% for field in f.visible_fields %}
23+
<div>
24+
{{ field.label }}
25+
{{ field }}
26+
{% for error in field.errors %}
27+
<span class="err">{{ error }}</span>
28+
{% endfor %}
29+
</div>
30+
{% endfor %}
2531
{% csrf_token %}
2632
<input type="submit" value="添加">
2733
</form>

Day31-Day35/car/templates/search2.html

+1
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@
7373

7474
</tbody>
7575
</table>
76+
<p>{{ last }}</p>
7677
</div>
7778
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
7879
<script>

0 commit comments

Comments
 (0)