django实现的投票系统详解
如何创建项目及应用,在《python的Web开发之Django框架应用(一)》一文中已经讲的很清楚了。在此,不作说明。
创建应用完成后,将应用添加到setting.py配置文件中。在INSTALLED_APPS中追加polls
执行如下命令:manage.py migrate,根据我们上一步安装的app应用生成相应的数据库表结构、索引等信息。此时我们用Navicat工具,查看数据库,可以看到一部分表。
修改polls/models.py文件,添加Question与Choice类。代码如下:
# -*- coding: utf-8 -*- from __future__ import unicode_literals 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执行数据库表的生成与同步,执行如下命令:
manage.py makemigrations polls
manage.py migrate
此时我们再观察数据库,会发现多了两张表,分别是polls_choice与polls_question表。
创建新的用户信息,执行如下命令:manage.py createsuperuser,输入用户名admin,邮箱地址,密码。
打开polls/admin.py文件,编写如下内容:
# -*- coding: utf-8 -*- from __future__ import unicode_literals 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)在浏览器地址栏输入**http://localhost:8000/admin/**即可看到登陆页面,输入我们上面建立的用户信息,进入投票系统的后台管理,完成数据的增删改查。
视图起着承前启后的作用,前是指前端页面,后是指后台数据库。将数据库表中的内容查询出来显示到页面上。
打开polls/views.py文件,编写如下内容:
# -*- coding: utf-8 -*- from __future__ import unicode_literals 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,)))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 url,include from django.contrib import admin urlpatterns = [ # url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls', namespace="polls")), url(r'^admin/', include(admin.site.urls)), ]模板就是前端页面,用来将数据显示到web页面上。
首先创建polls/templates/polls/目录,分别在该目录下创建index.html、detail.html和results.html文件。
index.html文件内容如下: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BtomTkBj-1593526080347)(http://odsh9s4s2.bkt.clouddn.com/django-toupiao-index.png)]
detail.html文件内容如下: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jaiQC9R2-1593526080349)(http://odsh9s4s2.bkt.clouddn.com/django-toupiao-detail.png)]
results.html文件内容如下: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zor0bMf9-1593526080351)(http://odsh9s4s2.bkt.clouddn.com/django-toupiao-results.png)]
浏览器地址栏输入**http://localhost:8000/polls/**,效果如下图: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-w7UPRLU7-1593526080354)(http://odsh9s4s2.bkt.clouddn.com/django-toupiao-pollsshow.png)]
查看投票结果: http://localhost:8000/polls/1/results/,效果如下图: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XfGJGdmk-1593526080359)(http://odsh9s4s2.bkt.clouddn.com/django-toupiao-resultsshow.png)]
http://www.cnblogs.com/fnng/p/4855743.html
http://www.cnblogs.com/djangochina/archive/2013/05/30/3108041.html
**https://docs.djangoproject.com/en/1.8/intro/tutorial03/**该链接是Django的官网。