一. 前台界面
这次做投票界面demo,前端主要就三个页面:
首页:展示最新的投票页面
详细页面:展示具体的投票内容
尾页:显示投票结果
(1) 添加视图函数
在poll/views.py上添加以下代码:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("欢迎来到投票系统!")
def detail(request, question_id):
return HttpResponse("将为您打开问卷%s" % question_id)
def results(request, question_id):
response = "正在查看问卷 %s 的结果"
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("请为问卷 %s 提交您的答案" % question_id)
再在路由poll/urls.py上添加对应的地址:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('<int:question_id>', views.detail),
path('<int:question_id>/results', views.results),
path('<int:question_id>/vote', views.vote),
# 使用尖括号获得网址部分后发送给视图函数作为一个关键字参数
]
注意这时候要将主路由中加上path('poll/', include('poll.urls'))
打开浏览器输入http://127.0.0.1:8000/poll/1,就可以看到以下画面
(2). 丰富视图功能(模板)
Django中提供了一套模板系统,可以将业务逻辑与页面显示样式分离。
在poll目录下创建templates文件夹,再在templates文件夹下创建poll文件夹,然后再在poll文件夹下面创建index.html文件。
整个项目目录结构就如下图所示,很清晰
将下面的代码写进html.index:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="/poll/{{ question.id }}/">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
接着修改views.py中的index视图:
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('poll/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))
此外,因为很多Django模板的工作原理都是这样的,所以我们可以用render()这个函数来简化操作,且能达到一样的效果。
from django.shortcuts import render
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
去浏览器看是一模一样的效果
二. 模板
(1). 简单应用
模板是Django中一个非常重要的内容,因此需要单独拿出来说一说。
我这里是新创建了一个项目来测试模板,在原项目上测试当然也是可以的。
项目的目录如下图所示:
hello_world.html:
<h1>{{ Hello1111 }}</h1>
变量要用双括号!
views.py:
from django.shortcuts import render
def hello_world(request):
context = {'Hello1111': 'Hello World!'}
return render(request, 'hello_world.html', context)
urls.py:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('hello', views.hello_world),
]
setting.py:
57 'DIRS': [os.path.join(BASE_DIR, 'template')],
(2). 更多语法和应用
这在下一篇博客再讲吧,太多了,挖个坑先~~