基于Django1.11和Python3开发一个简单的投票系统

简介:

一、创建一个VotingSystem项目以及polls应用

1
2
3
$ django - admin.py startproject VotingSystem
$ cd VotingSystem
$ python3 manage.py startapp polls

注:如果使用Pycharm来创建的话,以上两步都可以省略


二、配置tempaltes路径(如果没有)

a. 先在VotingSystem项目目录下新建一个templates文件夹,注意文件夹权限和属组

1
$ sudo mkdir templates

b. 然后再setting.py文件中添加路径

1
2
3
4
5
6
7
TEMPLATES  =  [
     {
         ...
         'DIRS' : [os.path.join(BASE_DIR,  'templates' )]
         ...
     },
]


三、将应用名称添加到setting.py文件INSTALLED_APPS选项末尾(如果没有)

1
2
3
4
INSTALLED_APPS  =  [
...
'polls' ,
]

注:以上两步如果用Pycharm都可以一步到位


四、编辑polls/model.py,创建数据库模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from  django.db  import  models
 
# 问题
class  Question(models.Model):
     question_text  =  models.CharField(max_length = 200 )
     
    # 双引号中定义的是在admin页面显示的verbose_name
     pub_date  =  models.DateTimeField( "date published" )  
     
     def  __str__( 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  __str__( self ):
         return  self .choice_text


五、同步数据库,生成数据库表(这里使用的是默认的sqlite3)

1
2
$ python3 manage.py makemigrations
$ python3 manage.py migrate


六、生成admin管理账户

1
$ python3 manage.py createsuperuser


七、将model注册到admin中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from  django.contrib  import  admin
from  .models  import  *
 
class  ChoiceInline(admin.TabularInline):
     model  =  Choice
     extra  =  3   # 在admin页面显示额外三个空白表单
 
class  QuestionAdmin(admin.ModelAdmin):
     fieldsets  =  [
         ( None , { 'fields' : [ 'question_text' ]}),
         ( 'Date information' , { 'fields' : [ 'pub_date' ],  'classes' : [ 'collapse' ]}),
     ]
     inlines  =  [ChoiceInline,]   # 在admin页面显示内联
     list_display  =  ( 'question_text' 'pub_date' )
 
admin.site.register(Question, QuestionAdmin)
admin.site.register(Choice)


八、启动server,进入admin页面,创建一些问题和选项

1
$ python3 manage.py runserver

wKiom1nbYXaTcdbFAAB5gZkafWA588.jpg-wh_50

wKiom1nbYduwsdzcAABxkzNKu34711.jpg-wh_50

wKioL1nbYYqRFAbQAAC0ZmMUnE0323.jpg-wh_50


九、编辑VotingSystem/urls.py,使用路由分发和命名空间

1
2
3
4
5
6
7
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" )),
]


十、编辑polls/urls.py

1
2
3
4
5
6
7
8
9
from  django.conf.urls  import  url
from  polls  import  views
 
urlpatterns  =  [
     url(r '^$' , views.index, name = "index" ),
     url(r '^(?P<question_id>[0-9]+)/$' , views.detail, name = "detail" ),
     url(r '^(?P<question_id>[0-9]+)/results/$' , views.results, name = "results" ),
     url(r '^(?P<question_id>[0-9]+)/vote/$' , views.vote, name = "vote" ),
]


十一、编辑polls/views.py视图文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from  django.shortcuts  import  render, get_object_or_404, HttpResponseRedirect, reverse, redirect
from  .models  import  *
 
# 首页,展示所有问题
def  index(req):
     lastest_question_list  =  Question.objects. all ()
     return  render(req,  "polls/index.html" locals ())
 
# 展示单个问题的所有选项
def  detail(req, question_id):
     question  =  get_object_or_404(Question, pk = question_id)
     return  render(req,  "polls/detail.html" locals ())
 
# 查看投票结果,   
def  results(req, question_id):    
     question  =  get_object_or_404(Question, pk = question_id)    
     return  render(req,  "polls/results.html" locals ())    
    
 
# 选择投票,设置cookie验证
def  vote(req, question_id):    
     =  get_object_or_404(Question, pk = question_id)    
     if  req.COOKIES.get( "is_vote" None ):    
         return  render(req,  "polls/detail.html" , { "question" : p,  "error_message" "你已经投过票了!" })    
     try :    
         selected_choice  =  p.choice_set.get(pk = req.POST[ 'choice' ])    
     except  (KeyError, Choice.DoesNotExist):    
         return  render(req,  "polls/detail.html" , { "question" : p,  "error_message" "You did't select a choice" })    
     else :    
         selected_choice.votes  + =  1    
         selected_choice.save()    
         rep  =  redirect(reverse( "polls:results" , args = (p. id ,)))    
         rep.set_cookie( "is_vote" True )    
         return  rep


十二、在templates目录下创建polls目录,在polls目录下创建index.html detail.html results.html三个HTML文件

index.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
< html  lang = "en" >
< head >
     < meta  charset = "UTF-8" >
     < title >Title</ title >
</ head >
< body >
{% if lastest_question_list %}
     < ul >
         {% for question in lastest_question_list %}
             < li >< a  href = "{% url 'polls:detail' question.id %}" >{{ question.question_text }}</ a ></ li >
         {% endfor %}
     </ ul >
{% else %}
     < p >No polls are avaiable.</ p >
{% endif %}
</ body >
</ html >

detail.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
< html  lang = "en" >
< head >
     < meta  charset = "UTF-8" >
     < title >Title</ title >
</ head >
< body >
< 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 = "提交" />
</ form >
</ body >
</ html >


results.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
< html  lang = "en" >
< head >
     < meta  charset = "UTF-8" >
     < title >Title</ title >
</ head >
< body >
< 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 %}" >再次投票</ a >
< a  href = "{% url 'polls:index' %}" >返回首页</ a >
</ body >
</ html >

十三、至此我们所有配置都已经配置完毕了,马上运行server,进行访问吧

http://127.0.0.1:8000/polls/


十四、githup源码地址: https://github.com/daibaiyang119/VotingSystem

本文转自戴柏阳的博客博客51CTO博客,原文链接http://blog.51cto.com/daibaiyang119/1971005如需转载请自行联系原作者


daibaiyang119


相关文章
|
15天前
|
算法 测试技术 开发者
性能优化与代码审查:提升Python开发效率
【4月更文挑战第9天】本文强调了Python开发中性能优化和代码审查的重要性。性能优化包括选择合适数据结构、使用生成器和避免全局变量,而代码审查涉及遵循编码规范、使用静态代码分析工具和编写单元测试。这些实践能提升代码效率和可维护性,促进团队协作。
|
1月前
|
监控 安全 应用服务中间件
python中Django入门(四)
python中Django入门(四)
31 0
|
15天前
|
安全 数据库 C++
Python Web框架比较:Django vs Flask vs Pyramid
【4月更文挑战第9天】本文对比了Python三大Web框架Django、Flask和Pyramid。Django功能全面,适合快速开发,但学习曲线较陡;Flask轻量灵活,易于入门,但默认配置简单,需自行添加功能;Pyramid兼顾灵活性和可扩展性,适合不同规模项目,但社区及资源相对较少。选择框架应考虑项目需求和开发者偏好。
|
5天前
|
前端开发 Java Go
开发语言详解(python、java、Go(Golong)。。。。)
开发语言详解(python、java、Go(Golong)。。。。)
|
7天前
|
Python
基于Django的Python应用—学习笔记—功能完善
基于Django的Python应用—学习笔记—功能完善
|
7天前
|
Python
Django开发——配置环境
Django开发——配置环境
|
9天前
|
前端开发 数据挖掘 API
使用Python中的Flask框架进行Web应用开发
【4月更文挑战第15天】在Python的Web开发领域,Flask是一个备受欢迎的轻量级Web框架。它简洁、灵活且易于扩展,使得开发者能够快速地构建出高质量的Web应用。本文将深入探讨Flask框架的核心特性、使用方法以及在实际开发中的应用。
|
13天前
|
JavaScript 前端开发 关系型数据库
金融技术解决方案:用Python和Vue开发加密货币交易平台
【4月更文挑战第11天】本文介绍了如何使用Python和Vue.js构建加密货币交易平台。首先确保安装了Python、Node.js、数据库系统和Git。后端可选择Flask或Django框架,通过RESTful API处理交易。前端利用Vue.js、Vuex和Vue Router创建用户友好的界面,并用Axios与后端通信。这种架构促进团队协作,提升代码质量和平台功能。
|
14天前
|
JavaScript 前端开发 Docker
全栈开发实战:结合Python、Vue和Docker进行部署
【4月更文挑战第10天】本文介绍了如何使用Python、Vue.js和Docker进行全栈开发和部署。Python搭配Flask创建后端API,Vue.js构建前端界面,Docker负责应用的容器化部署。通过编写Dockerfile,将Python应用构建成Docker镜像并运行,前端部分使用Vue CLI创建项目并与后端交互。最后,通过Nginx和另一个Dockerfile部署前端应用。这种组合提升了开发效率,保证了应用的可维护性和扩展性,适合不同规模的企业使用。
|
21天前
|
前端开发 测试技术 数据库
【python】为什么使用python Django开发网站这么火?
【python】为什么使用python Django开发网站这么火?