在student/view.py文件下编写代码
from django.shortcuts import render
# Create your views here.
def index(request):
"""首页"""
words = "Hello world!"
return render(request, 'index.html', context={'words':words})
定义函数index,参数为request,它是Django对用户发送过来的HTTP请求的封装。
函数返回值使用render渲染页面,使用了模板index.html。
然后在student目录下创建templates文件夹用来存放模板文件,templates文件夹为Django渲染页面时默认查找。
开始编写index.html代码
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学员管理系统title>
head>
<body>
欢迎登陆!{{ words }}
body>
html>
{{ words }} 使用Django模板语法,意思是从上下文中获取到words变量。这个变量在index调用时传递过来。
接下来配置URL。然用户访问URL时把数据发送到我们定义的index这个View上。
修改student目录下的urls.py文件
from django.contrib import admin
from django.conf.urls import url
from student.views import index
urlpatterns = [
url(r'^admin/', admin.site.urls), # 后台管理
url(r"^$", index, name="index"), # 网站首页
]
通过python manage.py runserver命令启动项目,访问http://127.0.0.1:8000
看到网站首页
通过admin后台创建几条学员数据
修改view.py中的代码
from django.shortcuts import render
from .models import Student
# Create your views here.
def index(request):
"""首页"""
words = "Hello studens!"
students = Student.objects.all()
context = {
'words': words,
'students': students,
}
return render(request, 'index.html', context)
通过Student模型拿到所有student的数据,接着把数据放到context里面传递到模板中。
接着修改index.html中的代码
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学员管理系统title>
head>
<body>
欢迎登陆!<br>
{{ words }}
<ul>
{% for student in students %}
<li>{{ student.name }} -- {{ student.get_status_display }}li>
{% endfor %}
ul>
body>
html>
{{ student.get_status_display }}对于设置了choices的字段,Django会帮我们提供一个方法,用来获取这个字段要展示的值。
在views.py的同级目录创建forms.py文件
from django import forms
from .models import Student
class StudentForm(forms.ModelForm):
"""学生数据表单"""
def clean_qq(self):
"""修改字段类型"""
cleaned_data = self.cleaned_data['qq']
if not cleaned_data.isdigit():
raise forms.ValidationError('必须是数字!')
return int(cleaned_data)
class Meta:
model = Student
fields = (
'name', 'sex', 'profession', 'email', 'qq', 'phone'
)
clean方法用来修改对应的字段类型
isdigit 方法主要用于检查其参数是否为十进制数字字符。
raise 触发异常后,后面的代码就不会再执行
如果验证失败,返回错误信息,其中错误信息将被存储在form中,最终被渲染到页面上。
在页面中展示Form,让用户能够通过填写信息提交表单,同时验证提交的数据是否符合要求,通过后再将其保存到数据库中。
修改view.py文件
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .forms import StudentForm
from .models import Student
# Create your views here.
def index(request):
"""首页"""
words = "Hello studens!"
students = Student.objects.all()
if request.method == 'POST': # 提交表单将通过post请求网站
form = StudentForm(request.POST)
if form.is_valid():
cleaned_date = form.cleaned_data
student = Student
student.name = cleaned_date['name']
student.sex = cleaned_date['sex']
student.email = cleaned_date['email']
student.profession = cleaned_date['profession']
student.qq = cleaned_date['qq']
student.phone = cleaned_date['phone']
student.save() # 保存到数据库
return HttpResponseRedirect(reverse('index')) # 成功后返回到网站首页
else:
form = StudentForm()
# 组织上下文
context = {
'form': form,
'words': words,
'students': students,
}
return render(request, 'index.html', context=context)
is_calia是一个校验机制
form.cleaned_data对象,它是Form根据字段类型对用户提交的数据做完转换之后的结果。
reverse方法,在urls.py中定义了index的时候,声明了name=‘index’,所以可以通过reverse来拿到对应的URL。
上面我们通过Student对象的方法来保存Student数据,其实在ModelForm中,因为有了Model的定义,所以手动构建Student的步骤可以省去,下面修改view.py的代码
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .forms import StudentForm
from .models import Student
# Create your views here.
def index(request):
"""首页"""
words = "Hello studens!"
students = Student.objects.all()
if request.method == 'POST': # 提交表单将通过post请求网站
form = StudentForm(request.POST)
if form.is_valid():
# cleaned_date = form.cleaned_data
# student = Student
# student.name = cleaned_date['name']
# student.sex = cleaned_date['sex']
# student.email = cleaned_date['email']
# student.profession = cleaned_date['profession']
# student.qq = cleaned_date['qq']
# student.phone = cleaned_date['phone']
form.save() # 保存到数据库
return HttpResponseRedirect(reverse('index')) # 成功后返回到网站首页
else:
form = StudentForm()
# 组织上下文
context = {
'form': form,
'words': words,
'students': students,
}
return render(request, 'index.html', context=context)
对于HTTP GET请求的数据,我们要将StudentForm的实例传到模板中
在模板中添加form,修改index.html的代码:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学员管理系统title>
head>
<body>
<h2>欢迎登陆!h2><br>
<h3><a href="/admin">管理员(admin)a>h3>
{{ words }}
<ul>
{% for student in students %}
<li>{{ student.name }} -- {{ student.get_status_display }}li>
{% endfor %}
ul>
<br />
<hr />
<form action="/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="提交">
form>
body>
html>
{% scrf_token %}是Django对提交数据安全性做的校验。post提交数据时加上{% scrf_token %}是防止跨站请求攻击的一种手段。
在view函数通过student = Student.objects.all()的方式获取到所有学生的数据
但考虑到后期会要求显示过滤之后的学生数据,所以调整view.py中的代码
from django.db import models
# Create your models here.
class Student(models.Model):
"""学生管理类"""
SEX_ITEMS = [
(1, '男'),
(2, '女'),
(0, '未知'),
]
STATUS_ITEMS = [
(0, '申请'),
(1, '通过'),
(2, '拒绝'),
]
name = models.CharField(max_length=128, verbose_name="姓名")
sex = models.IntegerField(choices=SEX_ITEMS, verbose_name="性别")
profession = models.CharField(max_length=30, verbose_name="职业")
email = models.EmailField(verbose_name="Email")
qq = models.CharField(max_length=20, verbose_name="QQ")
phone = models.CharField(max_length=20, verbose_name="电话")
status = models.IntegerField(choices=STATUS_ITEMS, default=0, verbose_name="审核状态")
create_time = models.DateTimeField(auto_now_add=True, editable=False, verbose_name="创建时间")
def __str__(self):
return '' .format(self.name)
@classmethod
def get_all(cls):
return cls.objects.all()
class Mete:
verbose_name = verbose_name_plural = "学员信息"
同时修改view.py中的代码:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .forms import StudentForm
from .models import Student
# Create your views here.
def index(request):
"""首页"""
words = "Hello studens!"
# students = Student.objects.all()
students = Student.get_all()
if request.method == 'POST': # 提交表单将通过post请求网站
form = StudentForm(request.POST)
if form.is_valid():
# cleaned_date = form.cleaned_data
# student = Student
# student.name = cleaned_date['name']
# student.sex = cleaned_date['sex']
# student.email = cleaned_date['email']
# student.profession = cleaned_date['profession']
# student.qq = cleaned_date['qq']
# student.phone = cleaned_date['phone']
form.save() # 保存到数据库
return HttpResponseRedirect(reverse('index')) # 成功后返回到网站首页
else:
form = StudentForm()
# 组织上下文
context = {
'form': form,
'words': words,
'students': students,
}
return render(request, 'index.html', context=context)