投票系统之详解

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. vuex 使用

    一.什么是Vuex Vuex是一个专门为Vue.js应用程序开发的状态管理模式, 它采用集中式存储管理所有组件的公共状态, 并以相应的规则保证状态以一种可预测的方式发生变化 二. 为什么要使用Vuex ...

  2. Java严选

    1,假如有两个线程,一个线程A,一个线程B都会访问一个加锁方法,可能存在并发情况,但是线程B访问频繁,线程A访问次数很少,问如何优化.(然后面试官说有了解过重度锁和轻度锁吗) a,竞争资源不激烈,选择 ...

  3. 菜鸟系列k8s——k8s集群部署(2)

    k8s集群部署 1. 角色分配 角色 IP 安装组件 k8s-master 10.0.0.170 kube-apiserver,kube-controller-manager,kube-schedul ...

  4. Elasticsearch-如何识别一篇文档

    ES-识别文档 为了识别同一个索引中的某篇文档,ES使用_uid中的文档类型和ID结合体._uid字段是由_id和_type字段组成,当搜索或者检索文档的时候总是能获得这两项信息. FengZhend ...

  5. PTA(Basic Level)1058.A+B in Hogwarts

    If you are a fan of Harry Potter, you would know the world of magic has its own currency system -- a ...

  6. ThreadPoolExecutor的重要参数

    一.ThreadPoolExecutor的重要参数 1.corePoolSize:核心线程数         * 核心线程会一直存活,及时没有任务需要执行         * 当线程数小于核心线程数时 ...

  7. 【C++ 补习】Copy Control

    C++ Primer 5th edition, chapter 13. The Rule of Three If a class needs a destructor, it almost surel ...

  8. 最长相同01数的子串(map搞搞)--牛客第三场 -- Crazy Binary String

    题意: 如题. 或者用我的数组分治也可以,就是有点愚蠢. //#include <bits/stdc++.h> #include <map> #include <iost ...

  9. 使用chattr禁止文件被删除

    chattr 是个啥? chattr 修改文件在Linux第二扩展文件系统(E2fs)上的特有属性 使用方法 +i or -i 设置/取消文件不能进行修改:即你不能删除它, 也不能给它重新命名,你不能 ...

  10. Windows Runtime (RT)

    学了sl for wp 开发了1年都没入门,只能说自己的学习欲望太低了. 今天偶然才发现wrt 跟 .net 是2个东西... orz. 得抛弃 sl ,wrt才是未来的主流吧... 这篇文章不错 h ...