In Django, web pages and other content are delivered by views. Each view is represented by a simple Python function (or method, in the case of class-based views).
-
带参数的views函数及对应URL格式
#polls/views.py
def detail(request, question_id):
return HTTPResponse("You're looking at question %s" % question_id)
#polls/urls.py
from django.conf.urls impor url
from . import views
urlpattern = [
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
]
注意url中正则表达式最前边的'?'号不可缺少
-
模板
在polls目录下创建templates文件夹,同时为了区别其它app的模板,在templates目录下再创建一个polls文件夹,并将关于polls应用的模板放在该目录下(polls/templates/polls/index.html)
# mysite/settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
# APP_DIR为True表示Django会默认去每个app目录下查找templates文件夹中的文件,直到找到所需模板
# 也可以通过修改'DIRS'对应的value值指定模板存放路径
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
],
},
},
]
views中的函数定义:
# polls/views.py
from django.http import HttpResponse
from django.template import loader
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))
index.html的模板样式:
<!--polls/templates/polls/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 %}
views中函数更简单的写法:
# polls/views.py
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)
-
引发404错误
在views.py中定义detail函数,并在未找到相应question时引发404错误
# polls/views.py
from django.http import Http404
from django.shortcuts import render
from .models import Question
# ...
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
# Object.DoesNotExist异常用于未能找到模型中的相应对象时
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/detail.html', {'question': question})
更简便的方法是使用Django自定义的get_object_or_404()方法
from django.shortcuts import get_object_or_404, render
from .models import Question
# ...
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
# get_object_or_404()方法的第一个参数是一个Django模型,第二个参数是一个关键字参数,该参数将会传入模型对象的get()方法中
return render(request, 'polls/detail.html', {'question': question})
# get_list_or_404()同get_object_or_404()工作原理类似,不同处在于get_list_or_404()方法将关键字参数传入模型对象的filter()方法中
-
在模板中改变URLs的硬编码形式
URLs的硬编码会使得以后改变URL样式时变得十分困难,因此需要改变成相对路径
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
# 模板会去polls/urls..py的urlpattern中查询name='detail'的url,并将参数一并传入
-
URL的名称空间
不同的应用中可能使用相同name的url,为了避免在进行{% url %}查询时引发混乱,最好在URLconf中添加名称空间
# polls/urls.py
from django.conf.urls import url
from . import views
# 名称空间方便{% url %}的查询
app_name = 'polls'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
相应模板中的{% url %}也应该更新
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
网友评论