Finished 3.4 Using template system

master
Jason Zhu 2020-10-20 16:19:00 +11:00
parent 63493eaeae
commit f91a6b6e25
3 changed files with 26 additions and 8 deletions

View File

@ -206,4 +206,21 @@ Here `path()` function is passed **route** and **view**; two additional option a
尝试用 get() 函数获取一个对象,如果不存在就抛出 Http404 错误也是一个普遍的流程。Django 也提供了一个快捷函数, 从而取代try/except语句 尝试用 get() 函数获取一个对象,如果不存在就抛出 Http404 错误也是一个普遍的流程。Django 也提供了一个快捷函数, 从而取代try/except语句
> 什么我们使用辅助函数 get_object_or_404() 而不是自己捕获 ObjectDoesNotExist 异常呢?还有,为什么模型 API 不直接抛出 ObjectDoesNotExist 而是抛出 Http404 呢? > 什么我们使用辅助函数 get_object_or_404() 而不是自己捕获 ObjectDoesNotExist 异常呢?还有,为什么模型 API 不直接抛出 ObjectDoesNotExist 而是抛出 Http404 呢?
> 因为这样做会增加模型层和视图层的耦合性。指导 Django 设计的最重要的思想之一就是要保证松散耦合。一些受控的耦合将会被包含在 django.shortcuts 模块中。 > 因为这样做会增加模型层和视图层的耦合性。指导 Django 设计的最重要的思想之一就是要保证松散耦合。一些受控的耦合将会被包含在 django.shortcuts 模块中。
### 3.4 Using template system
[Templates in Django](https://docs.djangoproject.com/en/3.1/topics/templates/)
`polls/detail.html` 模板里正式的代码:
```html
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
```
模板系统统一使用点符号来访问变量的属性

View File

@ -1 +1,6 @@
{{ question }} <h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>

View File

@ -1,20 +1,16 @@
from django.http import request, HttpResponse from django.http import request, HttpResponse
from django.shortcuts import render from django.shortcuts import render, get_object_or_404
from django.template import loader from django.template import loader
from .models import Question from .models import Question
def index(request): def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5] latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {'latest_question_list': latest_question_list} context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context) return render(request, 'polls/index.html', context)
def detail(request, question_id): def detail(request, question_id):
try: question = get_object_or_404(Question, pk=question_id)
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/detail.html', {'question': question}) return render(request, 'polls/detail.html', {'question': question})
def results(request, question_id): def results(request, question_id):