python 投票系统_Django 开发投票系统

本文详细介绍了如何在Windows 10环境下,利用Python 23.5和Django 1.9开发一个投票系统。从创建项目和应用,定义模型,设置后台管理,编写视图函数,实现投票功能,到设计模板和URL分发,一步步构建了一个完整的投票应用。用户无需登录即可查看问题并投票。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要参考官方文档

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

20180110214427155808.png

创建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

importdatetimefrom django.db importmodelsfrom django.utils.encoding importpython_2_unicode_compatiblefrom django.utils importtimezone#Create your models here.#问题

@python_2_unicode_compatibleclassQuestion(models.Model):

question_text= models.CharField(max_length=200)

pub_date= models.DateTimeField(‘date published‘)defwas_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):returnself.question_text#选择

@python_2_unicode_compatibleclassChoice(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 importadminfrom .models importQuestion, Choice#Register your models here.

classChoiceInline(admin.TabularInline):

model=Choice

extra= 3

classQuestionAdmin(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 importrender, get_object_or_404from django.http importHttpResponseRedirect, Http404from .models importQuestion, Choicefrom django.core.urlresolvers importreversefrom django.views importgenericfrom django.utils importtimezone#Create your views here.

#展示所有问题

classIndexView(generic.ListView):

template_name= ‘polls/index.html‘context_object_name= ‘latest_question_list‘

defget_queryset(self):#return the last five published question

return Question.objects.filter(pub_date__lte = timezone.now()).order_by(‘-pub_date‘)[:5]#查看问题详情

classDetailView(generic.DetailView):

model=Question

template_name= ‘polls/detail.html‘

defget_queryset(self):"""Excludes any questions that aren‘t published yet."""

return Question.objects.filter(pub_date__lte=timezone.now())#查看结果

classResultsView(generic.DeleteView):

model=Question

template_name= ‘polls/detail.html‘

#投票

defvote(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+= 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=(question.id,)))

5.模板

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

detail.html

{{ question.question_text }}

{% if error_message %}

{{ error_message }}

{% endif %}{% csrf_token %}

{% for choice in question.choice_set.all %}

{{ choice.choice_text }}
{% endfor %}

index.html

{% if latest_question_list %}

  • {% for question in latest_question_list %}
  • {{ question.question_text }}{% endfor %}
{% else %}

No polls are available.

{% endif %}

results.html

{{ question.question_text }}

  • {% for choice in question.choice_set.all %}
  • {{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}{% endfor %}

Vote again?

6.url分发

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

mysite/urls.py

from django.conf.urls importurl, includefrom django.contrib importadmin

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 importurlfrom . importviews

app_name= ‘polls‘urlpatterns=[#ex: /polls/

url(r‘^$‘, views.IndexView.as_view(), name=‘index‘),#ex: /polls/5/

url(r‘^(?P[0-9]+)/$‘, views.DetailView.as_view(), name=‘detail‘),#/polls/5/results/

url(r‘^(?P[0-9]+)/results/$‘, views.ResultsView.as_view(), name=‘results‘),#/polls/5/vote/

url(r‘^(?P[0-9]+)/vote/$‘, views.vote, name=‘vote‘),

]

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

登陆后:

20180110214427162644.png

20180110214427174363.png

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

20180110214427190965.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值