https://docs.djangoproject.com/en/1.8/intro/tutorial01/

参考官网文档,创建投票系统。

================

Windows  7/10

Python 2.7.10

Django 1.8.2

================

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

D:\pydj>django-admin.py startproject mysite

D:\pydj>cd mysite

D:\pydj\mysite>python manage.py startapp polls

添加到setting.py

# Application definition

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

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

D:\pydj\mysite>python manage.py makemigrations polls
Migrations for 'polls':
0001_initial.py:
- Create model Question
- Create model Choice
- Add field question to choice D:\pydj\mysite>python manage.py syncdb
……
You have installed Django's auth system, and don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'fnngj'):    用户名(默认当前系统用户名)
Email address: fnngj@126.com     邮箱地址
Password:     密码
Password (again):    重复密码
Superuser created successfully.

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容器:

D:\pydj\mysite>python manage.py runserver
Performing system checks... System check identified no issues (0 silenced).
October 05, 2015 - 13:08:12
Django version 1.8.2, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

  登录后台: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相关文章:

http://www.cnblogs.com/fnng/category/581256.html

Django快速开发之投票系统的更多相关文章

  1. Django快速开发投票系统

    使用Django搭建简单的投票系统:这个是官网的教程:https://docs.djangoproject.com/en/2.0/intro/tutorial01/ 在Run manage.py Ta ...

  2. Django快速搭建博客系统

    Django快速搭建博客系统 一.开发环境 Windows 7(64bit) python 3.6   https://www.python.org/ Django 2.0  https://www. ...

  3. 基于django快速开发一个网站(一)

    基于django快速开发一个网站(一) *  创建虚拟环境.基于虚拟环境创建django==2.0.0和图片加载库和mysql数据库驱动 1. 创建目录并创建虚拟环境 ╰$ mkdir Cornuco ...

  4. 程序小白如何快速开发OA办公系统

    对于企业开发oa办公系统,成本高,周期长.有些企业花高价购买,购买后受制于软件商,很多功能只能按原来设计需求走,无法升级或者升级慢.这些由于软件商的开发效率低难以及时地响应企业的需求变化,所以就有可能 ...

  5. Django快速开发实践:Drf框架和xadmin配置指北

    步骤 既然是快速开发,那废话不多说,直接说步骤: 安装Djagno 安装Django Rest Framework 定义models 定义Rest framework的serializers 定义Re ...

  6. 如何快速开发Winform应用系统

    在实际的业务中,往往还有很多需要使用Winform来开发应用系统的,如一些HIS.MIS.MES等系统,由于Winform开发出来的系统界面友好,响应快速,开发效率高等各方面原因,还有一些原因是独立的 ...

  7. Django博客开发教程,Django快速开发个人blog

    学DjangoWEB框架,估计大部分的朋友都是从Blog开发开始入门的,Django中文网发布了一个Django开发教程,这个教程简单易懂,能让你快速的使用Django开发一个漂亮的个人blog,是D ...

  8. django 快速实现完整登录系统

    django 实现完整登录系统 本操作的环境: =================== Windows 7 64 python3.5 Django 1.10 =================== 创 ...

  9. django 快速实现完整登录系统(cookie)

    经过前面几节的练习,我们已经熟悉了django 的套路,这里来实现一个比较完整的登陆系统,其中包括注册.登陆.以及cookie的使用. 本操作的环境: =================== deep ...

随机推荐

  1. requirejs按需加载angularjs文件

    之前分享了一篇用ocLazyLoad实现按需加载angular js文件的博客.本来当时想会使用一种方法就行了.可最近刚好有时间,在网上查找了一下requirejs实现angular js文件按需加载 ...

  2. JavaScript对异常的处理

    JavaScript提供了一套异常处理机制.当查出事故时,你的程序应该抛出一个异常: var add=function(a,b){ if(typeof a !== 'number' || typeof ...

  3. Canny边缘检测及图像缩放之图像处理算法-OpenCV应用学习笔记四

    在边缘检测算法中Canny颇为经典,我们就来做一下测试,并且顺便实现图像的尺寸放缩. 实现功能: 直接执行程序得到结果如下:将载入图像显示在窗口in内,同时进行图像两次缩小一半操作将结果显示到i1,i ...

  4. KVC/KVO简单实例代码

    Person.h #import<Foundation/Foundation.h> @classAccount; @interfacePerson :NSObject{ @private ...

  5. LEFT JOIN 多表查询的应用

    表结构如下:只把主要字段列出 表一:付款记录表  Gather 字段:GatherID , AccountID, PayMents 金额, PayWay  付款方式 1 现金 2 刷卡 表2:销售记录 ...

  6. 即时通信系统中如何实现:聊天消息加密,让通信更安全? 【低调赠送:QQ高仿版GG 4.5 最新源码】

    加密重要的通信消息,是一个常见的需求.在一些政府部门的即时通信软件中(如税务系统),对聊天消息进行加密是非常重要的一个功能,因为谈话中可能会涉及到机密的数据.我在最新的GG 4.5中,增加了对聊天消息 ...

  7. RCP:给GEF编辑器添加网格和标尺。

    网格和标尺效果如上图所示. 添加网格比较简单,也可以自己实现,主要思路是为编辑器添加一个GridLayer.但是还是建议参考eclipse自己的GEF样例来实现. 需要注意两个部分: 1.重写org. ...

  8. nginx(3、负载均衡)

    当业务系统需要配置集群时,会用到nginx的负载均衡功能.nginx提供如下几种: 1.轮询(默认):将不同的请求随机分配给配置的服务器,若出现宕机,则自动切换:轮询可配置weight值,即权重,权重 ...

  9. 认识SQLServer索引以及单列索引和多列索引的不同

     一.索引的概念 索引的用途:我们对数据查询及处理速度已成为衡量应用系统成败的标准,而采用索引来加快数据处理速度通常是最普遍采用的优化方法. 索引是什么:数据库中的索引类似于一本书的目录,在一本书中使 ...

  10. 不插网线,看不到IP的解决办法

    在Windows中,如果不插网线,就看不到IP地址,即使这个块网卡已经绑定了固定IP,原因是操作系统开启了DHCP Media Sense功能,该功能的作用如下: 在一台使用 TCP/IP 的基于 W ...