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 choiceD:\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 = Choiceextra = 3class 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 += 1selected_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 viewsurlpatterns = [# 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/voteurl(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 adminurlpatterns = [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快速开发之投票系统相关推荐
- [Django快速开发1]搭建一个简单的博客系统(1)
系列文章目录 Django快速开发0快速搭建环境并得到django项目的hello world 文章目录 系列文章目录 前言 从Django的模型层开始书写 定义文章模型: 使用脚本向sqlite3中 ...
- Django项目实战——用户投票系统(三)
Django项目实战--用户投票系统(三) 承接上文 官方文档链接附上: 编写你的第一个 Django 应用,第 3 部分 | Django 文档 | Django (djangoproject.co ...
- Django快速开发Web应用,开始项目
Django快速开发步骤 mkdir DIR_NAME 在创建的文件目录下创建虚拟环境 python3 -m venv VENV_NAME 激活虚拟环境 - source ./activate pyt ...
- 使用layuimini模块快速开发java后台系统模板(前后端分离)
使用layuimini模块快速开发后台系统模板(前后端分离) 下面已仓库管理系统为例(下面源码可自己下载来看) 1.登录界面login.html 下面的验证码使用的是Hutool 来实现的(Hutoo ...
- 基于smardaten无代码快速开发智慧城管系统
0️⃣需求背景 现代城市管理的面临着一系列问题:如执法人员不足.信息化手段应用少和时间处理不及时等,开发一个智慧城管回访系统的需求与日俱增- 通过引入智慧城管回访系统,可以提高城市管理的科学性.智能化 ...
- JNPF快速开发平台——业务流程系统(BPM)开发方案
项目简介 随着计算机技术的发展和互联网时代的到来,我们已经进入了信息时代,也称为数字化时代,在这数字化的时代里,企业的经营管理都受到了极大的挑战.从上世纪90年代起至今,企业的信息化工作开展的如火如荼 ...
- 【Django快速开发实战】(1~29)使用Django创建一个基础应用:职位管理系统
1.总体描述 1.1产品需求: 1.2职位管理系统-建模 1.3 Django项目代码结构 新增recruitment项目 django-admin startproject recruitment ...
- 微信投票系统java_微信刷票apijava开发微信投票系统
现在的投票活动根本就不是我们所想象的,呼朋唤友那么简单了,你一定要选择最专业的团队来帮助自己投票,只有通过微信,大家才能够更好的来进行投票,通过这种微信拉票的方式,完全可以给我们带来一系列的空间上的保 ...
- django 快速实现完整登录系统(cookie)
经过前面几节的练习,我们已经熟悉了django 的套路,这里来实现一个比较完整的登陆系统,其中包括注册.登陆.以及cookie的使用. 本操作的环境: =================== deep ...
最新文章
- ios button.imageview 和setimage的区别
- docker Cannot start container [8] System error: exec format error
- Keepalived配置日志文件
- inputstream 初始化_MyBatis初始化之加载初始化
- 数字化转型的认识模型
- 小叮咚切分词方法加入sourceforge.net中WebLucene分词模块
- 1-5 线性表元素的区间删除 (20 分)
- Visual Studio2017 数据库架构比较
- android tabhost的使用方法,Android TabHost组件使用方法详解
- hd4400 显卡opencore 下的 8个苹果问题解决方法
- Ubuntu16.04 开机开启小键盘数字键,时默认开NumLock灯
- 计算机未响应硬盘,最近电脑打开磁盘或文件夹老程序未响应为什么啊,有什么办法可以解决?...
- uni-app知识点整理
- 【C语言】fwrite 写如0X0A时,自动添加0X0D的解决方法
- Pycharm | cv2爆红 | opencv-python安装 | Requirement already satisfied: opencv-python 有效解决方法
- Shell编程中的数组定义、遍历
- 杨文俊的座右铭“君子欲讷于言而敏于行”
- 虚拟人乱战,技术才是王道
- 安卓应用商店上架从入门到精通到放弃
- 明辰智航云安网络与虚拟化性能管理系统—运维监控系统
热门文章
- 涨姿势,Java中New一个对象是个怎么样的过程?
- GBDT 算法如何用于分类问题
- 腾讯视频招GNN方向实习生啦~
- 模仿并超越人类围棋手,KL正则化搜索让AI下棋更像人类,MetaCMU出品
- 研究生穿实验服满校追羊跑... 因为这是在追奔跑的毕业论文,哈哈哈!
- Python之父:Python 4.0可能不会来了
- 「苹果牌」电动车要来了:最早明年见,还带着突破性电池技术
- 面试AI Lab能力测评
- ServiceMesh有关sidecar理解
- https://www.exploit-db.com/下载POC比较完善的代码