一、创建一个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.pyfrom django.conf.urls import url
from polls import views
urlpatterns = [
url(r'^$', views.index, name="index"),
url(r'^(?P[0-9]+)/$', views.detail, name="detail"),
url(r'^(?P[0-9]+)/results/$', views.results, name="results"),
url(r'^(?P[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())
# 选择投票,设置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:html>
Title{% if lastest_question_list %}
{% for question in lastest_question_list %}
{{ question.question_text }}{% endfor %}
{% else %}
No polls are avaiable.
{% endif %}
detail.html:html>
Title{{ question.question_text }}
{% if error_message %}
{{ error_message }}
{% endif %}
{% csrf_token %}
{% for choice in question.choice_set.all %}
{{ choice.choice_text }}
{% endfor %}
results.html:html>
Title{{ question.question_text }}
{% for choice in question.choice_set.all %}
{{ choice.choice_text }} --> {{ choice.votes }} vote{{ choice.votes|pluralize }}
{% endfor %}
再次投票
返回首页
十三、至此我们所有配置都已经配置完毕了,马上运行server,进行访问吧
http://127.0.0.1:8000/polls/