流程
1. 新建工程 test27
2. 新建应用 stu
python manage.py startapp stu
3. settings.py 新增加 INSTALLED_APPS stu
修改链接数据库 mysql
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'myapp',
'HOST': '127.0.0.1',
'PORT': '3306',
'USER': 'root',
'PASSWORD': '123456'
}
}
#修改 test27/__init__.py
import pymysql
pymysql.version_info = (1, 4, 13, "final", 0)
pymysql.install_as_MySQLdb()
4.修改 urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^student/',include('stu.urls'))
]
5.修改子路由 stu/urls.py
#coding:utf-8
from django.conf.urls import url
import views
urlpatterns = [
url(r'^$',views.index_view),
]
6.编辑 models.py 新增加模型类
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
#班级类(表一)
class Clazz(models.Model):
cno = models.AutoField(primary_key=True)
cname = models.CharField(max_length=30)
def __unicode__(self):
return u'Clazz:%s'%self.cname
#课程类(表二)
class Course(models.Model):
course_no = models.AutoField(primary_key=True)
course_name = models.CharField(max_length=30)
def __unicode__(self):
return u'Course:%s'%self.course_name
#学生类(表三)
class Student(models.Model):
sno = models.AutoField(primary_key=True)
sname = models.CharField(max_length=30)
cls = models.ForeignKey(Clazz)
cour = models.ManyToManyField(Course)
def __unicode__(self):
return u'Student:%s'%self.sname
#生成表
python manage.py migrate # 创建表结构
python manage.py makemigrations stu # 让 Django 知道我们在我们的模型有一些变更
python manage.py migrate stu # 创建表结构
#编辑 stu/views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
from .models import *
# Create your views here.
def index_view(request):
if request.method == 'GET':
return render(request,'register.html')
else:
sname = request.POST.get('sname','')
cname = request.POST.get('clsname','')
coursenames = request.POST.getlist('coursename',[])
#用函数封装 registerStu
flag = registerStu(sname,cname,*coursenames)
if flag:
return HttpResponse('注册成功')
return HttpResponse('注册失败')
#增加模板 register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/student/" method="post">
{% csrf_token %}
<p>
<label for="sn">姓名:</label><input name="sname" id="sn"/>
</p>
<p>
<label for="sc">所属班级:</label>
<select name="clsname" id="sc">
<option value="B201Python">B201Python</option>
<option value="B202Java">B202Java</option>
<option value="B203HTML5">B203HTML5</option>
</select>
</p>
<p>
<label>选课:</label>
<input type="checkbox" name="coursename" value="Python"/>Python  
<input type="checkbox" name="coursename" value="Java"/>Java  
<input type="checkbox" name="coursename" value="HTML5"/>HTML5  
</p>
<p>
<input type="submit" value="注册"/>
</p>
</form>
</body>
</html>
#编辑models.py
def getCls(cname):
try:
cls = Clazz.objects.get(cname=cname)
except Clazz.DoesNotExist:
cls = Clazz.objects.create(cname=cname)
return cls
def getCourseList(*coursenames):
courseList = []
for cn in coursenames:
try:
c = Course.objects.get(course_name=cn)
except Course.DoesNotExist:
c = Course.objects.create(course_name=cn)
courseList.append(c)
return courseList
def registerStu(sname,cname,*coursenames):
#获取班级对象
cls = getCls(cname)
#获取课程对象
courseList = getCourseList(*coursenames)
#插入学生表数据
try:
stu = Student.objects.get(sname=sname)
except Student.DoesNotExist:
stu = Student.objects.create(sname=sname,cls=cls)
#插入中间表数据
stu.cour.add(*courseList)
return True
#启动服务,查看数据表已完成插入。
#编辑 stu/urls.py,新增加
url(r'^showall/$',views.showall_view),
#编辑 stu/views.py,新增加
def showall_view(request):
cls = Clazz.objects.all()
return render(request,'showall.html',{'cls':cls})
#增加 templates/showall.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1" cellspacing="0" width="500px">
<tr>
<th>编号</th>
<th>班级名称</th>
<th>操作</th>
</tr>
{% for c in cls %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ c.cname }}</td>
<td>
<a href="/student/getstu/?cno={{ c.cno }}">详情</a>
</td>
</tr>
{% endfor %}
</table>
</body>
</html>
#编辑 stu/urls.py
url(r'^getstu/$',views.getstu)
#编辑 stu/views.py,新增加函数
def getstu(request):
cno = request.GET.get('cno',1)
no = int(cno)
#通过班级表退出学生
stus = Clazz.objects.get(cno=no).student_set.all()
return render(request,'stulist.html',{'stus':stus})
#新增加模板 stulist.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1" cellspacing="0" width="500px">
<tr>
<th>编号</th>
<th>姓名</th>
<th>班级名称</th>
<th>课程名称</th>
</tr>
{% for stu in stus %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ stu.sname }}</td>
<td>{{ stu.cls.cname }}</td>
<td>
{% for cou in stu.cour.all %}
{{ cou.course_name }}
{% endfor %}
</td>
</tr>
{% endfor %}
</table>
</body>
</html>