Skip to content

Commit 39f70bd

Browse files
committed
更新了Django第4天代码
1 parent a842830 commit 39f70bd

26 files changed

+735
-11
lines changed

Day31-Day35/car/car/__init__.py

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import pymysql
2+
3+
pymysql.install_as_MySQLdb()

Day31-Day35/car/car/settings.py

+127
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
"""
2+
Django settings for car project.
3+
4+
Generated by 'django-admin startproject' using Django 2.0.5.
5+
6+
For more information on this file, see
7+
https://docs.djangoproject.com/en/2.0/topics/settings/
8+
9+
For the full list of settings and their values, see
10+
https://docs.djangoproject.com/en/2.0/ref/settings/
11+
"""
12+
13+
import os
14+
15+
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
16+
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17+
18+
19+
# Quick-start development settings - unsuitable for production
20+
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
21+
22+
# SECURITY WARNING: keep the secret key used in production secret!
23+
SECRET_KEY = 'ol6dmf6im(w!l*z4w+_whm&)8@(c7%4&tlhd%uh6$lfx=pi*5e'
24+
25+
# SECURITY WARNING: don't run with debug turned on in production!
26+
DEBUG = True
27+
28+
ALLOWED_HOSTS = []
29+
30+
31+
# Application definition
32+
33+
INSTALLED_APPS = [
34+
'django.contrib.admin',
35+
'django.contrib.auth',
36+
'django.contrib.contenttypes',
37+
'django.contrib.sessions',
38+
'django.contrib.messages',
39+
'django.contrib.staticfiles',
40+
'search',
41+
]
42+
43+
MIDDLEWARE = [
44+
'django.middleware.security.SecurityMiddleware',
45+
'django.contrib.sessions.middleware.SessionMiddleware',
46+
'django.middleware.common.CommonMiddleware',
47+
'django.middleware.csrf.CsrfViewMiddleware',
48+
'django.contrib.auth.middleware.AuthenticationMiddleware',
49+
'django.contrib.messages.middleware.MessageMiddleware',
50+
'django.middleware.clickjacking.XFrameOptionsMiddleware',
51+
]
52+
53+
ROOT_URLCONF = 'car.urls'
54+
55+
TEMPLATES = [
56+
{
57+
'BACKEND': 'django.template.backends.django.DjangoTemplates',
58+
'DIRS': [os.path.join(BASE_DIR, 'templates')]
59+
,
60+
'APP_DIRS': True,
61+
'OPTIONS': {
62+
'context_processors': [
63+
'django.template.context_processors.debug',
64+
'django.template.context_processors.request',
65+
'django.contrib.auth.context_processors.auth',
66+
'django.contrib.messages.context_processors.messages',
67+
],
68+
},
69+
},
70+
]
71+
72+
WSGI_APPLICATION = 'car.wsgi.application'
73+
74+
75+
# Database
76+
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
77+
78+
DATABASES = {
79+
'default': {
80+
'ENGINE': 'django.db.backends.mysql',
81+
'NAME': 'car',
82+
'HOST': 'localhost',
83+
'PORT': 3306,
84+
'USER': 'root',
85+
'PASSWORD': '123456',
86+
}
87+
}
88+
89+
90+
# Password validation
91+
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
92+
93+
AUTH_PASSWORD_VALIDATORS = [
94+
{
95+
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
96+
},
97+
{
98+
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
99+
},
100+
{
101+
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
102+
},
103+
{
104+
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
105+
},
106+
]
107+
108+
109+
# Internationalization
110+
# https://docs.djangoproject.com/en/2.0/topics/i18n/
111+
112+
LANGUAGE_CODE = 'en-us'
113+
114+
TIME_ZONE = 'UTC'
115+
116+
USE_I18N = True
117+
118+
USE_L10N = True
119+
120+
USE_TZ = True
121+
122+
123+
# Static files (CSS, JavaScript, Images)
124+
# https://docs.djangoproject.com/en/2.0/howto/static-files/
125+
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
126+
127+
STATIC_URL = '/static/'

Day31-Day35/car/car/urls.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""car URL Configuration
2+
3+
The `urlpatterns` list routes URLs to views. For more information please see:
4+
https://docs.djangoproject.com/en/2.0/topics/http/urls/
5+
Examples:
6+
Function views
7+
1. Add an import: from my_app import views
8+
2. Add a URL to urlpatterns: path('', views.home, name='home')
9+
Class-based views
10+
1. Add an import: from other_app.views import Home
11+
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
12+
Including another URLconf
13+
1. Import the include() function: from django.urls import include, path
14+
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
15+
"""
16+
from django.contrib import admin
17+
from django.conf.urls import url
18+
19+
from search import views
20+
21+
urlpatterns = [
22+
url(r'^search$', views.search),
23+
url(r'^search2$', views.ajax_search),
24+
url(r'^add', views.add),
25+
url(r'^admin/', admin.site.urls),
26+
]

Day31-Day35/car/car/wsgi.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"""
2+
WSGI config for car project.
3+
4+
It exposes the WSGI callable as a module-level variable named ``application``.
5+
6+
For more information on this file, see
7+
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
8+
"""
9+
10+
import os
11+
12+
from django.core.wsgi import get_wsgi_application
13+
14+
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "car.settings")
15+
16+
application = get_wsgi_application()

Day31-Day35/car/manage.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#!/usr/bin/env python
2+
import os
3+
import sys
4+
5+
if __name__ == "__main__":
6+
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "car.settings")
7+
try:
8+
from django.core.management import execute_from_command_line
9+
except ImportError as exc:
10+
raise ImportError(
11+
"Couldn't import Django. Are you sure it's installed and "
12+
"available on your PYTHONPATH environment variable? Did you "
13+
"forget to activate a virtual environment?"
14+
) from exc
15+
execute_from_command_line(sys.argv)

Day31-Day35/car/search/__init__.py

Whitespace-only changes.

Day31-Day35/car/search/admin.py

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from django.contrib import admin
2+
3+
from search.models import CarRecord
4+
5+
6+
class CarRecordAdmin(admin.ModelAdmin):
7+
8+
list_display = ('carno', 'reason', 'date', 'punish', 'isdone')
9+
search_fields = ('carno', )
10+
11+
12+
admin.site.register(CarRecord, CarRecordAdmin)

Day31-Day35/car/search/apps.py

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
from django.apps import AppConfig
2+
3+
4+
class SearchConfig(AppConfig):
5+
name = 'search'
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# -*- coding: utf-8 -*-
2+
# Generated by Django 1.11 on 2018-05-24 01:16
3+
from __future__ import unicode_literals
4+
5+
from django.db import migrations, models
6+
7+
8+
class Migration(migrations.Migration):
9+
10+
initial = True
11+
12+
dependencies = [
13+
]
14+
15+
operations = [
16+
migrations.CreateModel(
17+
name='CarRecord',
18+
fields=[
19+
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
20+
('carno', models.CharField(max_length=7)),
21+
('reason', models.CharField(max_length=50)),
22+
('date', models.DateTimeField(db_column='happen_date')),
23+
('punlish', models.CharField(max_length=50)),
24+
('isdone', models.BooleanField(default=False)),
25+
],
26+
options={
27+
'db_table': 'tb_car_record',
28+
},
29+
),
30+
]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# -*- coding: utf-8 -*-
2+
# Generated by Django 1.11 on 2018-05-24 06:20
3+
from __future__ import unicode_literals
4+
5+
from django.db import migrations
6+
7+
8+
class Migration(migrations.Migration):
9+
10+
dependencies = [
11+
('search', '0001_initial'),
12+
]
13+
14+
operations = [
15+
migrations.AlterModelOptions(
16+
name='carrecord',
17+
options={'ordering': ('-date',)},
18+
),
19+
migrations.RenameField(
20+
model_name='carrecord',
21+
old_name='punlish',
22+
new_name='punish',
23+
),
24+
]

Day31-Day35/car/search/migrations/__init__.py

Whitespace-only changes.

Day31-Day35/car/search/models.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from django.db import models
2+
3+
4+
class CarRecord(models.Model):
5+
carno = models.CharField(max_length=7)
6+
reason = models.CharField(max_length=50)
7+
date = models.DateTimeField(db_column='happen_date', auto_now_add=True)
8+
punish = models.CharField(max_length=50)
9+
isdone = models.BooleanField(default=False)
10+
11+
@property
12+
def happen_date(self):
13+
return self.date.strftime('%Y-%m-%d %H:%M:%S')
14+
"""
15+
return '%d年%02d月%02d日 %02d:%02d:%02d' % \
16+
(self.date.year, self.date.month, self.date.day,
17+
self.date.hour, self.date.minute, self.date.second)
18+
"""
19+
20+
class Meta:
21+
db_table = 'tb_car_record'
22+
ordering = ('-date', )

Day31-Day35/car/search/tests.py

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from django.test import TestCase
2+
3+
# Create your tests here.

Day31-Day35/car/search/views.py

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

0 commit comments

Comments
 (0)