文章目录
下列html文件中使用的都是模版语言,比较简单大家自己查查我就不赘述了。
和数据库、模版连接的index视图
views.py
from django.http import HttpResponse, Http404
from django.shortcuts import render, get_object_or_404
from django.template import loader
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')
# 上下文字典
context = {
"latest_question_list": latest_question_list
}
# 通过获取到的模版去渲染
# template = loader.get_template('index.html') # polls/templates/index.html
# return HttpResponse(template.render(context, request))
# 上述代码的作用是,载入 index.html 模板文件,并且向它传递一个上下文(context)。
# 这个上下文是一个字典,它将模板内的变量映射为 Python 对象。
# 「载入模板,填充上下文,再返回由它生成的 HttpResponse 对象」是一个非常常用的操作流程。
# 于是 Django 提供了一个快捷函数,我们用它来重写 index() 视图:
# 通过 render 快速渲染
return render(request, 'index.html', context)
index.html
位置 : polls/templates/index.html
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
去除模版中的应编码 URL
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
问题在于,硬编码和强耦合的链接,对于一个包含很多应用的项目来说,修改起来是十分困难的。
然而,因为你在 polls.urls 的 url() 函数中通过 name 参数为 URL 定义了名字,你可以使用 {% url %} 标签代替它:
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
如果地址在别的app中,可以在其对应app 中的urls.py中加上 app_name = 'polls'
from django.urls import path
from . import views
app_name = 'polls'
...
这样就可以指定app了
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
抛出404错误的detail视图
polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<question_id>/', views.detail, name='detail'), # 我们detail的对应关系
]
views.py
from django.http import HttpResponse, Http404
from django.shortcuts import render, get_object_or_404
from django.template import loader
from .models import Question
...
def detail(request, question_id):
# 检测到空抛出异常
"""
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
"""
# 尝试用 get() 函数获取一个对象,如果不存在就抛出 Http404 错误也是一个普遍的流程。
# Django 也提供了一个快捷函数,下面是修改后的详情 detail() 视图代码:
# 如果不存在直接抛出一个异常
question = get_object_or_404(Question, pk=question_id)
# 也有 get_list_or_404() 函数,工作原理和 get_object_or_404() 一样,除了 get() 函数被换成了 filter() 函数。
# 如果列表为空的话会抛出 Http404 异常。
return render(request, "detail.html", {"question": question})
detail.html
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>