【Django】【二】模板
【代码】
settings.py
"""
Django settings for guest project.
Generated by 'django-admin startproject' using Django 1.11.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'nvz+#19d=3x%-iqhyqpr@82^#1+bw_@j13k8m!id$oe%v-ecql'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sign',
'bootstrap3',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'guest.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'guest.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST':'127.0.0.1',
'PORT':'3306',
'NAME':'guest',
'USER':'root',
'PASSWORD':'',
'OPTIONS':{
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
}
}
'''
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
'''
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
urls.py
"""guest URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from sign import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.index),
url(r'^index/$',views.index),
url(r'^accounts/login/$',views.index),
url(r'^login_action/$',views.login_action),
url(r'^event_manage/$',views.event_manage),
url(r'^search_name/$',views.search_name),
url(r'^guest_manage/$',views.guest_manage),
url(r'^sign_index/(?P<event_id>[0-9]+)/$',views.sign_index),
url(r'^sign_index_action/(?P<event_id>[0-9])/$',views.sign_index_action),
url(r'^logout/$',views.logout),
]
views.py
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect
from sign.models import Event,Guest
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
# Create your views here.
#首页
def index(request):
return render(request, 'index.html')
#return HttpResponse('Hello Django!')
'''
#cookie
#登录动作
def login_action(request):
if request.method == 'POST':
username = request.POST.get('username','')
password = request.POST.get('password','')
if username == 'admin' and password == 'admin123':
response = HttpResponseRedirect('/event_manage/')
response.set_cookie('user',username,3600)
return response
else:
return render(request,'index.html',{'error':'username or password error!'})
else:
return render(request,'index.html',{'error':'username or password error!'})
#发布会管理
def event_manage(request):
username = request.COOKIES.get('user','')
return render(request,'event_manage.html',{'user':username})
'''
'''
#认证登录 使用 admin 管理后台创建用户账户来验证登录功能
def login_action(request):
if request.method == 'POST':
username = request.POST.get('username','')
password = request.POST.get('password','')
user = auth.authenticate(username=username,password=password)
if user is not None:
auth.login(request,user)
request.session['user'] = username
response = HttpResponseRedirect('/event_manage')
return response
else:
return render(request,'index.html',{'error':'username or password error!'})
else:
return render(request,'index.html',{'error':'username or password error!'})
'''
#session
#登录动作
def login_action(request):
if request.method == 'POST':
username = request.POST.get('username','')
password = request.POST.get('password','')
if username == 'admin' and password == 'admin123':
response = HttpResponseRedirect('/event_manage')
request.session['user'] = username
return response
else:
return render(request,'index.html',{'error':'username or password error!'})
else:
return render(request,'index.html',{'error':'username or password error!'})
#发布会管理
#@login_required #【备注】不注释就总是跳到登录页,不知道为啥
def event_manage(request):
event_list = Event.objects.all()
username = request.session.get('user','')
return render(request,'event_manage.html',{'user':username,'events':event_list})
#发布会名称搜索
#@login_required
def search_name(request):
username = request.session.get('user','')
search_name = request.GET.get('name','')
event_list = Event.objects.filter(name__contains=search_name)
return render(request,'event_manage.html',{'user':username,'events':event_list})
#嘉宾管理
#@login_required
def guest_manage(request):
username = request.session.get('user','')
guest_list = Guest.objects.all()
paginator = Paginator(guest_list,2)
page = request.GET.get('page')
try:
contacts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer,deliver first page.
contacts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g.9999),deliver last page os results.
contacts = paginator.page(paginator.num_pages)
return render(request,'guest_manage.html',{'user':username,'guests':contacts})
#签到页面
#@login_required
def sign_index(request,event_id):
event = get_object_or_404(Event,id=event_id)
return render(request,'sign_index.html',{'event':event})
#签到功能
#@login_required
def sign_index_action(request,event_id):
event = get_object_or_404(Event,id=event_id)
phone = request.POST.get('phone','')
result = Guest.objects.filter(phone=phone)
if not result:
return render(request,'sign_index.html',{'event':event,'hint':'phone error.'})
result = Guest.objects.filter(phone=phone,event_id=event_id)
if not result:
return render(request,'sign_index.html',{'event':event,'hint':'event id or phone error.'})
result = Guest.objects.get(phone=phone,event_id=event_id)
if result.sign:
return render(request,'sign_index.html',{'event':event,'hint':'user has sign in.'})
else:
Guest.objects.filter(phone=phone,event_id=event_id).update(sign = '1')
return render(request,'sign_index.html',{'event':event,'hint':'sign in success','guest':result})
#退出登录
#@login_required
def logout(request):
auth.logout(request)
response = HttpResponseRedirect('/index/')
return response
templates/event_manage.html
<html lang="zh-CN">
<head>
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
<title>Guest Manage</title>
</head>
<body role="document">
<!-- 导航栏 -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/event_manage/">Guest Manage System</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">发布会</a></li>
<li><a href="/guest_manage/">嘉宾</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">{{user}}</a></li>
<li><a href="/logout/">退出</a></li>
</ul>
</div>
</div>
</nav>
<!--发布会搜索表单-->
<div class="page-header" style="padding-top:60px;">
<div id="navbar1" class="navbar-collapse collapse">
<form class="navbar-form" method="get" action="/search_name/">
<div class="form-group">
<input name="name" type="text" placeholder="名称" class="form-control">
</div>
</form>
</div>
</div>
<!-- 发布会列表 -->
<div class="row" style="padding-top: 80px;">
<div class="col-md-6">
<table class="table table-striped">
<thead>
<tr>
<th>id</th><th>名称</th><th>状态</th><th>地址</th><th>时间</th><th>签到</th>
</tr>
</thead>
<tbody>
{% for event in events %}
<tr>
<td>{{ event.id }}</td>
<td>{{ event.name }}</td>
<td>{{ event.status }}</td>
<td>{{ event.address }}</td>
<td>{{ event.start_time }}</td>
<td>
<a href="/sign_index/{{event.id}}/" target="{{event.id}}_blank">sign</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</body>
</html>
templates/guest_manage.html
<!DOCTYPE html>
<html lang="en">
<head>
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
<title>Guest Manage</title>
</head>
<body role="document">
<!- 导航栏 -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/event_manage/">Guest Manage System</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="/event_manage/">发布会</a></li>
<li class="active"><a href="#">嘉宾</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">{{user}}</a></li>
<li><a href="/logout/">退出</a></li>
</ul>
</div>
</div>
</nav>
<!-- 嘉宾列表 -->
<div class="row" style="padding-top: 80px;">
<div class="col-md-6">
<table class="table table-striped">
<thead>
<tr>
<th>id</th>
<th>名称</th>
<th>手机</th>
<th>Email</th>
<th>签到</th>
<th>发布会</th>
</tr>
</thead>
<tbody>
{% for guest in guests %}
<tr>
<td>{{guest.id}}</td>
<td>{{guest.realname}}</td>
<td>{{guest.phone}}</td>
<td>{{guest.email}}</td>
<td>{{guest.sign}}</td>
<td>{{guest.event}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<!-- 列表分页器 -->
<div class="pagination">
<span class="step-links">
{% if guests.has_previous %}
<a href="?page={{ guests.prevous_page_number}}">previous</a>
{% endif %}
<span class="current">
Page {{guests.number}} of {{guests.paginator.num_pages}}.
</span>
{% if guests.has_next %}
<a href="?page={{ guests.next_page_number }}">next</a>
{% endif %}
</span>
</div>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Django Page</title>
</head>
<body>
<h1>发布会管理</h1>
<form method="post" action="/login_action/">
<input name="username" type="text" placeholder="username"><br>
<input name="password" type="password" placeholder="password"><br>
{{ error }}<br>
<button id="bth" type="submit">登录</button>
</form>
</body>
</html>
templates/sign_index.html
<!DOCTYPE html>
<html lang="en">
<head>
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
<title>签到</title>
</head>
<body>
<!-- 导航栏 -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">{{ event.name }}</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="/event_manage/">发布会</a></li>
<li><a href="/guest_manage/">嘉宾</a></li>
</ul>
</div>
</div>
</nav>
<!-- 签到功能 -->
<div class="page-header" style="padding-top: 80px;">
<div id="navbar1" class="navbar-collapse collapse">
<form class="navbar-form" method="post" action="/sign_index_action/{{event.id}}/">
<div class="form-group">
<input name="phone" type="text" placeholder="输入手机号" class="form-control">
</div>
<button type="submit" class="btn btn-success">签到</button>
<font color="red">
<br>{{ hint}}
<br>{{ guest.realname }}
<br>{{ guest.phone }}
</font>
</form>
</div>
</div>
</body>
</html>
1. Django-bootstrap3
guest>python -m pip install django-bootstrap3
源码 https://github.com/defnngj/guest3
本章将使用Bootstrap前端框架结合Django来开发Web页面
Django-bootstrap3项目是将 Bootstrap3集成到Django中,作为Django的一个应用提供。好处是在Django中用Bootstrap会变的更加方便。
在.../guest/settings.py文件中添加bootstrap3应用
...
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sign',
'bootstrap3',
]
5.2 发布会管理
本节完成发布会管理列表与发布会名称搜索功能的开发。
5.2.1 发布会列表
../sign/views.py
from sign.models import Event
...
# 发布会管理
@login_required
def event_manage(request):
event_list = Event.objects.all()
username = request.session.get('user', '')
return render(request, 'event_manage.html', {'user': username,
'events': event_list})
../templates/event_manage.html
<!DOCTYPE html>
<html lang="en">
<head>
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
<title>Guest Manage</title>
</head>
<body role="document">
<!-- 导航栏 -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/event_manage/">Guest Manage System</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">发布会</a></li>
<li><a href="/guest_manage/">嘉宾</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">{{ user }}</a></li>
<li><a href="/logout/">退出</a></li>
</ul>
</div>
</div>
</nav>
<!-- 发布会列表 -->
<div class="row" style="padding-top: 80px; padding-left: 50px; padding-right: 50px;">
<div class="co1-mod-6">
<table class="table table-striped">
<thead>
<tr>
<th>id</th><th>名称</th><th>状态</th><th>地址</th><th>时间</th>
</tr>
</thead>
<tbody>
{% for event in events %}
<tr>
<td>{{ event.id }}</td>
<td>{{ event.name }}</td>
<td>{{ event.status }}</td>
<td>{{ event.address }}</td>
<td>{{ event.start_time }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</body>
</html>
{%%}为Django模版语言的标签
{{}}为Django的模版语言标签,用于定义显示变量。
5.2.2 搜索功能
.. /templats/event_manage.html
..
<!-- 导航栏 -->
...
<!-- 发布会搜索栏-->
<div class="page-header" style="padding-top: 60px;">
<div id="navbar1" class="navbar-collapse collapse">
<form class="navbar-form" method="get" action="/search_name/">
<div class="form-group">
<input name="name" type="text" placeholder="名称" class="form-control">
</div>
<button type="submit" class="btn btn-success">搜索</button>
</form>
</div>
</div>
<!-- 发布会列表 -->
...
../guest/urls.py
...
url(r'^search_name/$', views.search_name),
../sign/views.py
...
# 发布会名称搜索
@login_required
def search_name(request):
username = request.session.get('user', '')
search_name = request.GET.get('name', '')
event_list = Event.objects.filter(name__contains=search_name)
return render(request, 'event_manage.html', {'user': username,
'events': event_list})
5.3 嘉宾管理
../templates/guest_manage.html
<!DOCTYPE html>
<html lang="en">
<head>
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
<title>Guest Manage</title>
</head>
<body role="document">
<!-- 导航栏 -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/event_manage/">Guest Manage System</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li ><a href="/event_manage/">发布会</a></li>
<li><a class="active">嘉宾</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">{{ user }}</a></li>
<li><a href="/logout/">退出</a></li>
</ul>
</div>
</div>
</nav>
<!-- 嘉宾列表 -->
<div class="row" style="padding-top: 80px; padding-left: 50px; padding-right: 50px;">
<div class="co1-mod-6">
<table class="table table-striped">
<thead>
<tr>
<th>id</th><th>名称</th><th>手机</th><th>Email</th><th>签到</th><th>发布会</th>
</tr>
</thead>
<tbody>
{% for guest in guests %}
<tr>
<td>{{ guest.id }}</td>
<td>{{ guest.realname }}</td>
<td>{{ guest.phone }}</td>
<td>{{ guest.email }}</td>
<td>{{ guest.sign }}</td>
<td>{{ guest.event }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</body>
</html>
../guest/urls.py
...
url(r'^guest_manage/$', views.guest_manage),
../sign/views.py
..
from sign.models import Event, Guest
...
#嘉宾管理
@login_required
def guest_manage(request):
username = request.session.get('user', '')
guest_list = Guest.objects.all()
return render(request, 'guest_manage.html', {'user': username,
'guests': guest_list})
5.3.2 分页器
对于嘉宾管理页面来说,当前需要一个分页功能,一场发布会需要由几千位嘉宾参加。
Django提供了Paginator类来实现分类功能。分页功能略微复杂,首先进入Django的shell模式, 练习Paginator类的基本使用,请在嘉宾表至少添加5条信息
B0178RQ2019070018:guest wangxue$ python3 manage.py shell
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 03:13:28)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.core.paginator import Paginator
>>> from sign.models import Guest
>>> guest_list = Guest.objects.all()
>>> p = Paginator(guest_list, 2) # 创建每页2条数据的分页器
<string>:1: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'sign.models.Guest'> QuerySet.
>>> p.count # 查看共多少条数据
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/cursors.py:166: Warning: (3135, "'NO_ZERO_DATE', 'NO_ZERO_IN_DATE' and 'ERROR_FOR_DIVISION_BY_ZERO' sql modes should be used with strict mode. They will be merged with strict mode in a future release.")
result = self._query(query)
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/cursors.py:166: Warning: (3090, "Changing sql mode 'NO_AUTO_CREATE_USER' is deprecated. It will be removed in a future release.")
result = self._query(query)
5
>>> p.page_range
range(1, 4) # 查看共分多少页(每页2条数据),循环结果为1,2,3(共3页)
##################第一页##############################
>>> page1 = p.page(1) # 获取第一页数据
>>> page1 # 当前第几页
<Page 1 of 3>
>>> page1.object_list # 当前页的对象
<QuerySet [<Guest: jack>, <Guest: andy>]> # 循环打印第一页嘉宾的realname
>>> for g in page1:
... g.realname
...
'jack'
'andy'
>>>
##########################第二页######################################
>>> page2 = p.page(2) # 获取第二页数据
>>> page2.start_index() # 本页第一条数据
3
>>> page2.end_index() # 本页最后一条数据
4
>>> page2.has_next() # 是否有下一页
True
>>> page2.has_previous() # 是否有上一页
True
>>> page2.previous_page_number() # 上一页是第几页
1
>>> page2.next_page_number() # 下一页是第几页
3
###################################第三页#############################################
>>> page3 = p.page(3)
>>> page3.has_next()
False
>>> page3.has_previous()
True
>>> page3.has_other_pages()
True
>>> page3.previous_page_number()
2
下面就来实现分页功能吧
../sign/views.py
....
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
...
#嘉宾管理
@login_required
def guest_manage(request):
username = request.session.get('user', '')
guest_list = Guest.objects.all()
paginator = Paginator(guest_list, 2)
page = request.GET.get('page')
try:
contacts = paginator.page(page)
except PageNotAnInteger:
# 如果page不是整数, 取第一页数据
contacts = paginator.page(1)
except EmptyPage:
# 如果page不在范围, 取最后一页
contacts = paginator.page(paginator.num_pages)
return render(request, 'guest_manage.html', {'user': username,
'guests': contacts})
.. /templates/guest_manage.html
...
<!-- 嘉宾列表 -->
.....
<!-- 列表分页器-->
<div class="pagination">
<span class="step-links">
{% if guests.has_previous %}
<a href="?page={{ guests.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ guests.number }} of {{ guests.paginator.num_pages }}
</span>
{% if guests.has_next %}
<a href="?page={{ guests.next_page_number }}">next</a>
{% endif %}
</span>
</div>
5.4 签到功能
../templates/event_manage.html
增加一列签到标签
.......
<th>id</th><th>名称</th><th>状态</th><th>地址</th><th>时间</th><th>签到</th>
</tr>
</thead>
<tbody>
{% for event in events %}
<tr>
<td>{{ event.id }}</td>
<td>{{ event.name }}</td>
<td>{{ event.status }}</td>
<td>{{ event.address }}</td>
<td>{{ event.start_time }}</td>
<td>
<a href="/sign_index/{{ event.id }}/" target="{{ event.id }}_blank">sign</a>
</td>
......
访问http://127.0.0.1:8000/event_manage/
target="{{ event.id }}_blank" 属性设置链接在新窗口打开
..../guests/urls.py
...
url(r'^sign_index/(?P<eid>[0-9]+)/$', views.sign_index),
此处与之前添加的路径在匹配方式上略有不同。
(?P<eid>[0-9]+) 匹配发布会ID, 而且必须是数字。匹配的数字eid将会作为sign_index()的参数
5.4.2 签到页面
../sign/views.py
...
from django.shortcuts import render, get_list_or_404
...
# 签到页面
@login_required
def sign_index(request, eid):
event = get_object_or_404(Event, id=eid)
return render(request, 'sign_index.html', {'event': event})
sign_index()获取从URL配置得到的eid, 作为发布会ID的查询条件
这里又学到了一个有用的方法 get_object_or_404() 她默认调用table.objects.get() 如果查询的对象不存在,则会抛出Http404异常。这就省去了对table.objects.get()方法的异常断言。
创建../templates/sign_index.html页面
<!DOCTYPE html>
<html lang="en">
<head>
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
<title>Guest Manage</title>
</head>
<body role="document">
<!-- 导航栏 -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">{{ event.name }}</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li ><a href="/event_manage/">发布会</a></li>
<li><a href="/guest_manage/">嘉宾</a></li>
</ul>
</div>
</div>
</nav>
<!-- 签到功能 -->
<div class="page-header" style="padding-top: 80px; padding-left: 50px; padding-right: 50px;">
<div id="navbar" class="navbar-collapse collapse">
<form class="navbar-form" method="post" action="/sign_index_action/{{ event.id }}/">
<div class="form-group">
<input name="phone" type="text" placeholder="输入手机号" class="form-control">
</div>
<button type="submit" class="btn btn-success">签到</button>
<font color="red">
<br>{{ hint }}
<br>{{ guest.realname }}
<br>{{ guest.phone }}
</font>
</form>
</div>
</div>
</body>
</html>
{{hint}}用于显示签到成功和失败的提示信息;
嘉宾签到页
5.4.3 签到功能
../guest/urls.py
...
url(r'^sign_index_action/(?P<eid>[0-9]+)/$', views.sign_index_action),
打开.../sign/views.py
# 签到动作
@login_required
def sign_index_action(request, eid):
event = get_object_or_404(Event, id=eid) # 注意这里是get_object_or_404 不是get_list_or_404
phone = request.POST.get('phone', '')
print (phone)
result = Guest.objects.filter(phone=phone)
if not result:
return render(request, 'sign_index.html', {'event': event,
'hint': 'phone error.'})
result = Guest.objects.filter(phone=phone, event_id=eid)
if not result:
return render(request, 'sign_index.html', {'event': event,
'hint': 'event id or phone error.'})
result = Guest.objects.get(phone=phone, event_id=eid) # 注意这里是get
if result.sign:
return render(request, 'sign_index.html', {'event': event,
'hint': 'user has sign in.'})
else:
Guest.objects.filter(phone=phone, event_id=eid).update(sign='1')
return render(request, 'sign_index.html', {'event': event,
'hint': 'sign in success!',
'guest': result})
1
2
3
4
5.5 退出系统
.../urls.py
...
url(r'^logout/$', views.logout),
.../sign/views.py
...
#退出登陆
@login_required
def logout(request):
auth.logout(request)
response = HttpResponseRedirect('/index/')
return response
Django 不但提供了auth.login()用于验证登陆用户信息, 同时也提供了auth.logout() 用于系统的推出,他可以清除浏览器保存的用户信息,所以,不用再考虑如何删除浏览器cookie的问题了。
当退出成功后默认跳转到/index/路径