主要参考官方文档

Windows  10

Python 23.5

Django 1.9

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

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

D:\python>cd mysite

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

创建app后将app加入到setting中,打开mysite/setting.py,将polls这个应用添加进去

INSTALLED_APPS = [
'polls.apps.PollsConfig', 'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

2.创建模型

打开polls/models.py

import datetime
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone # Create your models here.
# 问题
@python_2_unicode_compatible
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published') def was_published_recently(self):
now = timezone.now()
return timezone.now()-datetime.timedelta(days=1) <= self.pub_date <= now was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?' def __str__(self):
return self.question_text # 选择
@python_2_unicode_compatible
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete = models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0) def __str__(self):
return self.choice_text

运行命令:python manage.py makemigrations 和python manage.py migrate全数据库生成相应的表

3.后台管理

打开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']}),
]
inlines = [ChoiceInline] list_filter = ['pub_date']
list_display = ('question_text', 'pub_date', 'was_published_recently')
search_fields = ['question_text'] admin.site.register(Question, QuestionAdmin)

4.编写视图函数(展示)

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, Http404
from .models import Question, Choice
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone # Create your views here. # 展示所有问题
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list' def get_queryset(self):
#return the last five published question
return Question.objects.filter(pub_date__lte = timezone.now()).order_by('-pub_date')[:5] # 查看问题详情
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html' def get_queryset(self):
"""
Excludes any questions that aren't published yet.
"""
return Question.objects.filter(pub_date__lte=timezone.now())
# 查看结果
class ResultsView(generic.DeleteView):
model = Question
template_name = 'polls/detail.html' # 投票
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {'question': question, '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=(question.id,)))

5.模板

视图函数处理的结果通过模板展示出来

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>

index.html

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

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>

6.url分发

不同的url在这里进行分发到不同的函数处理

mysite/urls.py

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

再次分发

polls/urls.py

#coding:utf-8
#!/usr/bin/env python from django.conf.urls import url
from . import views app_name = 'polls'
urlpatterns = [
# ex: /polls/
url(r'^$', views.IndexView.as_view(), name='index'),
# ex: /polls/5/
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
# /polls/5/results/
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
# /polls/5/vote/
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

输入命令python manage.py runserver,运行系统

登陆后:

不登陆,可以查看到相应的问题,选中相应的小圆点,点击vote可进行投票。

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

  1. Django快速开发投票系统

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

  2. django用户投票系统详解

    投票系统之详解 1.创建项目(mysite)与应用(polls) django-admin.py startproject mysite python manage.py startapp polls ...

  3. Django开发点菜系统学习笔记

    1.使用django-simple-captcha包的时候,会调用到: register_form = RegisterForm(request.POST) 但是这个时候captcha不进行错误检验, ...

  4. Django快速开发之投票系统

    https://docs.djangoproject.com/en/1.8/intro/tutorial01/ 参考官网文档,创建投票系统. ================ Windows  7/1 ...

  5. Django写的投票系统2(转)

    在上一篇中 django实例:创建你的第一个应用投票系统(一) 已经介绍基本的功能,并已经启动服务了.这一节介绍数据库相关的东东. 首页打开mysite/settings.py配置文件, 设置数据库打 ...

  6. Django写的投票系统1(转)

    当然主要是从django的帮助文档里面来的,权当是翻译吧 这个投票系统的主要功能有 1.一个前台页面,可以让用户来投票 2.一个管理员页面,可以用来添加.修改.删除投票 首页第一步要确定你已经安装了D ...

  7. 纯django开发博客系统

    企业级教程:纯django开发博客系统 1.视频教程 https://www.duanshuilu.com/ 2.教程文档 https://www.duanshuilu.com/ 0.课程简介1.简价 ...

  8. JavaWeb项目开发案例精粹-第2章投票系统-006view层

    1.index.jsp <%@ page language="java" import="java.util.*" pageEncoding=" ...

  9. django开发个人简易Blog——数据模型

    提到数据模型,一定要说一下MVC,MVC框架是现代web开发中最流行的开发框架,它将数据与业务逻辑分开,减小了应用之间的高度耦合.个人非常喜欢MVC开发框架,除了具有上述特性,它使得web开发变得非常 ...

随机推荐

  1. java问题排查可能用到的一些命令

    1. jmap查询jvm内存使用情况 -heap :打印jvm heap的情况 -histo: 打印jvm heap的直方图.其输出信息包括类名,对象数量,对象占用大小. -histo:live : ...

  2. new date() 在Linux下引起的时间差问题

    java工程部署到Linux时,使用new date()获取的时间出现时间差,通过查阅资料,发现有可能是服务器时间设置问题,JVM问题,jdk问题: 1.服务器时间设置问题: 正确的时间显示 有 CS ...

  3. 解决导入myeclipse的项目注释和中文是乱码

    1.先说真正解决我所遇到的问题的办法. 用记事本打开——另存为——格式改为UTF-8——保存后在myeclipse就正常显示了. 2.以下是网上找到的办法,试了一些并没有解决问题,但或许是中间必须的步 ...

  4. 转载《android:scaleType属性》

    在网上查了好多资料,大致都雷同,大家都是互相抄袭的,看着很费劲,不好理解,自己总结一下,留着需要看的话来查找. 代码中的例子如下: <ImageView android:id="@+i ...

  5. 【Cocos2d-x 3.x】 事件处理机制源码分析

    在游戏中,触摸是最基本的,必不可少的.Cocos2d-x 3.x中定义了一系列事件,同时也定义了负责监听这些事件的监听器,另外,cocos定义了事件分发类,用来将事件派发出去以便可以实现相应的事件. ...

  6. 第四篇T语言实例开发,自动加血

    游戏自动加血 基础知识复习 通过前面的学习了解以下内容: TC软件的基本使用 TC的基础语法 变量与常量 功能的使用 流程语句的使用 线程的基本使用 TC控件的基本使用 热键和按钮的事件功能 控件的数 ...

  7. 【LINUX命令】之MV

    linux下重命名文件或文件夹的命令mv既可以重命名,又可以移动文件或文件夹. 例子:将目录A重命名为B mv A B 例子:将/a目录移动到/b下,并重命名为c mv /a /b/c 注意: mv命 ...

  8. (转)AppiumLibrary基本操作

    *** Settings *** Library AppiumLibrary Library Collections Library String Library Dialogs *** Test C ...

  9. 百度网盘kbengine - warring项目下载地址

    http://pan.baidu.com/s/1k4J4y 下载解压之后,请看<<使用说明.doc>>,有更新指导

  10. 关于post请求超出最大长度

    这是因为asp.net默认限制最大上传文件大小为4096kb,而我上传了6000kb+所以超出了限制,需要修改项目的web.config文件即可解决,可以将最大文件长度设置为你需要的长度,我这里设置为 ...