Django doc summary (4)

View

In Django, each view is represented by a simple python function.

To get from a URL to view, Django uses what are know as 'URLconfs'. A URL conf maps URL patterns to views.

Now we edit the samapp views.py to add three functions.They are 'detail', 'results' and vote'.

def detail(request, question_id):
	return HttpResponse("You're looking at question %s." %question_id)

def results(request, question_id):
	response = "You're looking at the results of question %s."
	return HttpResponse(response % question_id)


def vote(request, question_id):
	return HttpResponse("You're voting on question %s." % question_id)

Then we should edit the 'samapp/urls.py' file to take the three functions in action.

# /samapp/
url(r'^$', views.index, name='index'),
# /samapp/23/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
# /samapp/23/results/
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
# /samapp/23/vote/
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),

A view that actually do something

views.py

def index(request):
	latest_question_list = Question.objects.order_by('-pub_date')[:5]
	output = ', '.join([q.question_teext for q in latest_question_list])
	#return HttpResponse("Hello, this is sam site.")
	return HttpResponse(output)

Template system ###

Next, let's use Django's template system to separate the design from python by creating a template that the view can use.

The template file position should like below.

├─samapp
│  │
│  ├─templates
│  │  └─samapp
│  │          index.html

index.html

{% if latest_question_list %}
    <ul>
        {% for question in latest_question_list %}
            <li>
                <a href="/samapp/{{ question.id }}/">
                    {{ question.question_text }}
                </a>
            </li>
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

Then, we update the samapp/views.py to use the template.

def index(request):
	latest_question_list = Question.objects.order_by('-pub_date')[:5]
	template = loader.get_template('samapp/index.html')
	context = RequestContext(request, {'latest_question_list': latest_question_list})
	return HttpResponse(template.render(context))

A shortcut: render() ###

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)

A shortcut: 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)
    return render(request, 'polls/detail.html', {'question': question})

Removing hardcoded URLs in templates

As before, in the template, the link war partially hardcoded link this:

<a href="/samapp/{{ question.id }}/">
    {{ question.question_text }}
</a>

That is tightly-coupled approached with url '/samapp/'.So, we'd better do like this.

<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

This will look up the URL definition in the samapp/urls.py file. And if you want to change the URL, you would change only int the samapp/urls.py file.

Namespacing URL names

When we have more than one apps, we will encounter a problem.
The url name may be the same. So, we should add namespaces to our URL conf.

from django.conf.urls import 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'),
]

Now, change the template from the origin to the below.

<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
posted @ 2015-12-10 22:32  sam_rui  阅读(168)  评论(0编辑  收藏  举报