投票系统之详解

1、创建项目(mysite)与应用(polls)

django-admin.py startproject mysite
python manage.py startapp polls

添加到setting.py

INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)

2、创建模型(即数据库)

一般web开发先设计数据库,数据库设计好了,项目就完了大半了,可见数据库的重要性。打开polls/models.py编写如下:

 coding=utf-8
from django.db import models # Create your models here.
# 问题
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published') def __unicode__(self):
return self.question_text # 选择
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0) def __unicode__(self):
return self.choice_text

执行数据库表生成与同步。

python manage.py makemigrations polls
python manage.py syncdb

3、admin管理

 django提供了强大的后台管理,对于web应用来说,后台必不可少,例如,当前投票系统,如何添加问题与问题选项?直接操作数据库添加,显然麻烦,不方便,也不安全。所以,管理后台就可以完成这样的工作。

打开polls/admin.py文件,编写如下内容:

from django.contrib import admin
from .models import Question, Choice # Register your models here.
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3 class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date') admin.site.register(Choice)
admin.site.register(Question, QuestionAdmin)

  当前脚本的作用就是将模型(数据库表)交由admin后台管理。

运行web容器:

登录后台:http://127.0.0.1:8000/admin

登录密码就是在执行数据库同步时设置的用户名和密码。

点击“add”添加问题。

4、编写视图

视图起着承前启后的作用,前是指前端页面,后是指后台数据库。将数据库表中的内容查询出来显示到页面上。

编写polls/views.py文件:

# coding=utf-8
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from .models import Question, Choice # Create your views here.
# 首页展示所有问题
def index(request):
# latest_question_list2 = Question.objects.order_by('-pub_data')[:2]
latest_question_list = Question.objects.all()
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context) # 查看所有问题
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question}) # 查看投票结果
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question}) # 选择投票
def vote(request, question_id):
p = get_object_or_404(Question, pk=question_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))

5、配置url

url是一个请求配置文件,页面中的请求转交给由哪个函数处理,由该文件决定。

 首先配置polls/urls.py(该文件需要创建)

from django.conf.urls import url
from . import views urlpatterns = [
# ex : /polls/
url(r'^$', views.index, name='index'),
# ex : /polls/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
# ex : /polls/5/results/
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
# ex : /polls/5/vote
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

 接着,编辑mysite/urls.py文件。

from django.conf.urls import include, url
from django.contrib import admin urlpatterns = [
url(r'^polls/', include('polls.urls', namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
]

6、创建模板

模板就是前端页面,用来将数据显示到web页面上。

首先创建polls/templates/polls/目录,分别在该目录下创建index.html、detail.html和results.html文件。

index.html

{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}

detail.html

<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>

results.html

<h1>{{ question.question_text }}</h1>

<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul> <a href="{% url 'polls:detail' question.id %}">Vote again?</a>

7、功能展示

启动web容器,访问:http://127.0.0.1:8000/polls/





django用户投票系统详解的更多相关文章

  1. Linux 系统的用户和组详解_【all】

    1.Linux 用户和用户组详解 2.Linux 文件特殊权限详解 3.Linux 文件的读写执行权限的说明 4.Linux 架构之简述企业网站 5.Linux 环境变量设置详解 6.企业生产环境用户 ...

  2. java中的io系统详解 - ilibaba的专栏 - 博客频道 - CSDN.NET

    java中的io系统详解 - ilibaba的专栏 - 博客频道 - CSDN.NET 亲,“社区之星”已经一周岁了!      社区福利快来领取免费参加MDCC大会机会哦    Tag功能介绍—我们 ...

  3. Linux 用户及权限详解

    Linux 用户及权限详解 用户 , 组 ,权限 安全上下文(secure context): 权限: r,w,x 文件: r : 可读,可以使用类似cat 等命令查看文件内容. w : 可写,可以编 ...

  4. Vmware12安装centos系统详解

    vmware12安装centos7系统详解 用虚拟机12安装centos7系统详细安装过程,后附centos7下载地址. 工具/原料 虚拟机12 centos7系统镜像 方法/步骤 1 1.百度搜索c ...

  5. centos7.2环境nginx+mysql+php-fpm+svn配置walle自动化部署系统详解

    centos7.2环境nginx+mysql+php-fpm+svn配置walle自动化部署系统详解 操作系统:centos 7.2 x86_64 安装walle系统服务端 1.以下安装,均在宿主机( ...

  6. syslog之一:Linux syslog日志系统详解

    目录: <syslog之一:Linux syslog日志系统详解> <syslog之二:syslog协议及rsyslog服务全解析> <syslog之三:建立Window ...

  7. Django框架 之 querySet详解

    Django框架 之 querySet详解 浏览目录 可切片 可迭代 惰性查询 缓存机制 exists()与iterator()方法 QuerySet 可切片 使用Python 的切片语法来限制查询集 ...

  8. 搭建zabbix监控系统详解

    搭建zabbix监控系统详解 文:warren   博文大纲:一.前言 二.zabbix监控架构三.搭建Zabbix监控服务器四.搭建过程中遇到有些服务无法正常启动的解决办法 一.前言 : 要想实时的 ...

  9. Bootstrap栅格系统详解,响应式布局

    Bootstrap栅格系统详解 栅格系统介绍 Bootstrap 提供了一套响应式.移动设备优先的流式栅格系统,随着屏幕或视口(viewport)尺寸的增加,系统会自动分为最多12列. 栅格系统用于通 ...

随机推荐

  1. 阶段3 3.SpringMVC·_05.文件上传_5 文件上传之跨服务器上传分析和搭建环境

    使用这个jar包来跨服务器上传 搞两个tomcat.一个springmvc一个fileupload 选中tomcat server点击左边的加号 需要改端口和JMX pport这个端口 部署文件上传的 ...

  2. message-digest algorithm 5

    using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptograph ...

  3. 强大的BeautifulSoup

    Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库·它能够通过你喜欢的转换器实现惯用的文档导航 安装BeautifulSoup 推荐使用Beautiful Sou ...

  4. MySQL 查看约束,添加约束,删除约束 添加列,修改列,删除列

    查看表的字段信息:desc 表名; 查看表的所有信息:show create table 表名; 添加主键约束:alter table 表名 add constraint 主键 (形如:PK_表名) ...

  5. DFS(深度优先搜索)和BFS(广度优先搜索)

    深度优先搜索算法(Depth-First-Search) 深度优先搜索算法(Depth-First-Search),是搜索算法的一种. 它沿着树的深度遍历树的节点,尽可能深的搜索树的分支. 当节点v的 ...

  6. flask add_url_rule的使用

    from flask import Flask,url_for #url_for 接受两个参数(endpoint,**value)endpoint没有指定就是默认的函数名,根据 view_func._ ...

  7. 【案例分享】SpreadJS金融行业应用实践,开发基于Web Excel的指标补录平台

    SpreadJS作为一款基于 HTML5 的纯前端电子表格控件,以“高速低耗.高度类似Excel.可无限扩展”为产品特色,提供移动跨平台和浏览器支持,可同时满足 .NET.Java.App 等应用程序 ...

  8. Java基础(九)

    综合案例 此前我们已经练习了根据集合当中的字符串对象读写文件,而本综合案例主要练习根据集合当中的自定义对象来读写文件. 场景介绍 很多网络游戏当中都有组队模式,例如魔兽世界.DotA.英雄联盟(LOL ...

  9. java中start()、yield、setDeamon()

    本节主要说明以下三个问题 start()的启动顺序不代表线程的启动顺序 yeild的作用 守护线程 1.start()与线程启动顺序 package foreverly.cn.chapter1; pu ...

  10. STM32程序内存分布

    参考文献:https://www.rt-thread.org/document/site/programming-manual/basic/basic/ 一般 MCU 包含的存储空间有:片内 Flas ...