更新时间:2022-09-21 09:32:46
一、创建一个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 |
九、编辑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):
p = 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