官方教程#3-视图

2017-09-14  本文已影响0人  wangfp

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).

#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中正则表达式最前边的'?'号不可缺少


# 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)

# 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()方法中

<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
# 模板会去polls/urls..py的urlpattern中查询name='detail'的url,并将参数一并传入

# 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>
上一篇 下一篇

猜你喜欢

热点阅读