Django快速开发之投票系统

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

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

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/

 

==========

时间: 2024-09-19 09:10:52

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

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

经过前面几节的练习,我们已经熟悉了django 的套路,这里来实现一个比较完整的登陆系统,其中包括注册.登陆.以及cookie的使用. 本操作的环境: =================== deepin linux 2013(基于ubuntu) python 2.7 Django 1.6.2 ===================   创建项目与应用                                                                        

运维前线:一线运维专家的运维方法、技巧与实践2.5 使用Django快速构建CMDB系统

2.5 使用Django快速构建CMDB系统 2.5.1 Django介绍 Django是一个免费的.开源的Web框架,由Python语言编写,由于其是在一个快节奏的新闻编译室环境中开发出来的,因此它的设计目的是让普通开发者的工作变得简单.Django遵循模型-视图-控制器(MVC)框架模式,目前由一个非盈利的独立组织的软件基金会(DSF)维持. Django鼓励快速开发和干净实用的设计.Django可以更容易更快速地构建更好的Web应用程序.它是由经验丰富的开发人员来创建的,省去了Web开发的

AgileEAS.NET平台开发实例-药店系统-快速的SAAS开发体验

一.AgileEAS.NET应用开发简介 在4月份,callhot写过一系列的有关于AgileEAS.NET平台的开发应用的系列AgileEAS.NET平台开发Step By Step系列-药店系统-索引,他通过一个接近于实际应用的案例,从头到尾的向大家展示了AgileEAS.NET平台在企业信息系统开发中的应用及其应用开发的过程. AgileEAS.NET平台是一套应用系统快速开发平台,用于帮助中小软件开发商快速构建自己的企业信息管理类开发团队,以达到节省开发成本.缩短开发时间,快速适应市场变

django 快速搭建blog

如果本文看不懂的,去看的我视频吧! http://www.testpub.cn/ ------------------------------------------- Django 自称是"最适合开发有限期的完美WEB框架".本文参考<Django web开发指南>,快速搭建一个 blog 出来,在中间涉及诸多知识点,这里不会详细说明,如果你是第一次接触Django ,本文会让你在感性上对Django有个认识,完成本文操作 后会让你有兴趣阅读的相关书籍和文档. 废话少说,

用ASP.NET 2.0设计网络在线投票系统

asp.net|设计|投票|网络|在线 一.系统功能设计和数据库设计 1.系统功能设计和数据库设计 1.1 系统功能设计 网络在线投票系统实现的功能比较简单,具体如下: ◎投票项目的管理: ◎添加投票的项目: ◎删除投票的项目: ◎对项目进行投票: ◎查看项目的投票情况. 1.2 数据库设计 本系统的数据库设计比较简单,只需要存储投票的信息即可.在SQL Server 2000中创建一个数据库,名称为"WebVoteDB",并在该数据库中创建投票项目表Votes.其中"Vot

PHP开发高效WEB系统的技巧讲解

通过对PHP语言的学习,大家知道它是一门功能强大的计算机语言,被许多程序员用来开发网站.接下来我们将为大家介绍PHP开发高效WEB系统的相关绩效. PHP开发高效WEB系统小项目 - 简单而直接的PHP   一般对于一个功能页面在20以下的网站,我们可以用一个很简单的框架结构来写.在这个规模上,我建议是使用比较直接的面向过程编码方法,原因很简单,没有必要把class文件弄的N 多,结果controller里边就一个new就完了.当然,需求频繁变化的项目除外. 在这个级别上,php优点表现的很明显

用VC6.0集成环境快速开发VxD

VxD (Virtual Device Driver), 即虚拟设备驱动程序, 是运行在处理器Ring0特权级别的驱动程序,可以执行任何处理器指令,访问机器中的任何数据寄存器.VxD被用作Windows 9x系统和物理设备之间的接口,扩展了WINDOWS 系统的核心服务,能够访问和控制实际的硬件环境. 随着WIN 2000和新一代的设备驱动程序WDM(Windows Driver Model)推出,预计VxD将慢慢过时,而现实情况却是:随便打开一种网络计数器的统计窗口就会发现,Windows 9

用于Flex和Java快速开发的Flamingo项目

Exadel的Flamingo项目是一个快速启动后台使用Java构建的RIA应用的工具.在中间层,该工具对Seam和Spring都提供了支持.在 展现层,Flamingo既支持Flex也支持JavaFX.该工具启动应用程序开发的方式与AppFuse项目类似,后者可用于更传统的Java Web层框架.InfoQ与Exadel的Igor Polevoy和Fima Katz进行了交谈以了解更多关于Flamingo的信息. Igor和Fima以分享Flamingo的特性细节作为开场白.现在的特性可以被划

多用户商城系统SKMall怎么样?好用吗?大家有没有比较好的开发多用户商城系统的公司推荐?谢谢了!

问题描述 多用户商城系统SKMall怎么样?好用吗?大家有没有比较好的开发多用户商城系统的公司推荐?谢谢了! 多用户商城系统SKMall怎么样?好用吗?大家有没有比较好的开发多用户商城系统的公司推荐?谢谢了! 解决方案 这个估计需要根据你自己的需求进行定制,没有可以推荐的公司. 解决方案二: 是闪酷团队据十年电商从业经历,结合多个大型电商项目实施经验,历时近3年时间,精心研发出的电子商务系统,也是目前国内最领先,最完善的电商软件产品,主要包括商家管理系统.用户下单系统.运营管理系统等,更完善的诠