一、创建一个VotingSystem项目以及polls应用
$ django-admin.py startproject VotingSystem $ cd VotingSystem $ python3 manage.py startapp polls
注:如果使用Pycharm来创建的话,以上两步都可以省略
二、配置tempaltes路径(如果没有)
a. 先在VotingSystem项目目录下新建一个templates文件夹,注意文件夹权限和属组
$ sudo mkdir templates
b. 然后再setting.py文件中添加路径
TEMPLATES = [ { ... ‘DIRS‘: [os.path.join(BASE_DIR, ‘templates‘)] ... }, ]
三、将应用名称添加到setting.py文件INSTALLED_APPS选项末尾(如果没有)
INSTALLED_APPS = [ ... ‘polls‘, ]
注:以上两步如果用Pycharm都可以一步到位
四、编辑polls/model.py,创建数据库模型
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)
$ python3 manage.py makemigrations $ python3 manage.py migrate
六、生成admin管理账户
$ python3 manage.py createsuperuser
七、将model注册到admin中
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页面,创建一些问题和选项
$ python3 manage.py runserver
九、编辑VotingSystem/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")), ]
十、编辑polls/urls.py
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视图文件
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()) # 选择投票 def vote(req, question_id): p = get_object_or_404(Question, pk=question_id) 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() return redirect(reverse("polls:results", args=(p.id,)))
十二、在templates目录下创建polls目录,在polls目录下创建index.html detail.html results.html三个HTML文件
index.html:
<!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:
<!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:
<!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
本文出自 “戴柏阳的博客” 博客,请务必保留此出处http://daibaiyang119.blog.51cto.com/3145591/1971005
基于Django1.11和Python3开发一个简单的投票系统
原文地址:http://daibaiyang119.blog.51cto.com/3145591/1971005