<p>如果要为同一个URL模式使用不同的模板,请不要在<code>urls.py</code>中硬编码模板。相反,请路由到<a href="https://docs.djangoproject.com/en/1.8/topics/http/views/" rel="nofollow">view function</a>(或者,也可以路由到<code>views.py</code>中的一个<a href="https://docs.djangoproject.com/en/1.8/topics/class-based-views/" rel="nofollow">class-based view</a>),它根据您的条件向不同的模板进行调度。这正是<code>views.py</code>的用途和通常的使用方式。在</p>
<p>有关如何将URL路由到视图函数,请参阅<a href="https://docs.djangoproject.com/en/1.8/intro/tutorial03/" rel="nofollow">Django tutorial part 3</a>。(如果您正在学习Django,您可能需要在第1部分中<a href="https://docs.djangoproject.com/en/1.8/" rel="nofollow">start</a>。)</p>
<p>在本教程中引入了<code>render</code>快捷方式时,对<a href="https://docs.djangoproject.com/en/1.8/intro/tutorial03/#a-shortcut-render" rel="nofollow">the example</a>进行了调整,一个发送到不同模板的视图可能如下所示:</p>
<pre class="lang-py prettyprint-override"><code>from django.shortcuts import render
from .models import Question
def index(request):
if request.user.is_admin():
return render(request, 'polls/admin-index.html', {})
else:
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
</code></pre>