Philosophy
A view is a “type” of Web page in your Django application that generally serves a specific function and has a specific template. For example, in a weblog application, you might have the following views:- Blog homepage – displays the latest few entries.
- Entry “detail” page – permalink page for a single entry.
- Year-based archive page – displays all months with entries in the given year.
- Month-based archive page – displays all days with entries in the given month.
- Day-based archive page – displays all entries in the given day.
- Comment action – handles posting comments to a given entry.
- Poll “archive” page – displays the latest few polls.
- Poll “detail” page – displays a poll question, with no results but with a form to vote.
- Poll “results” page – displays results for a particular poll.
- Vote action – handles voting for a particular choice in a particular poll.
Design your URLs
The first step of writing views is to design your URL structure. You do this by creating a Python module, called a URLconf. URLconfs are how Django associates a given URL with given Python code.When a user requests a Django-powered page, the system looks at the ROOT_URLCONF setting, which contains a string in Python dotted syntax. Django loads that module and looks for a module-level variable called urlpatterns, which is a sequence of tuples in the following format:
(regular expression, Python callback function [, optional dictionary])
When it finds a match, Django calls the Python callback function, with an HttpRequest object as the first argument, any "captured" values from the regular expression as keyword arguments, and, optionally, arbitrary keyword arguments from the dictionary (an optional third item in the tuple).
For more on HttpRequest objects, see the Request and response objects. For more details on URLconfs, see the URL dispatcher.
When you ran django-admin.py startproject mysite at the beginning of Tutorial 1, it created a default URLconf in mysite/urls.py. It also automatically set your ROOT_URLCONF setting (in settings.py) to point at that file:
ROOT_URLCONF = 'mysite.urls'
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^polls/$', 'mysite.polls.views.index'),
(r'^polls/(?P\d+)/$' , 'mysite.polls.views.detail'),
(r'^polls/(?P\d+)/results/$' , 'mysite.polls.views.results'),
(r'^polls/(?P\d+)/vote/$' , 'mysite.polls.views.vote'),
(r'^admin/', include(admin.site.urls)),
)
detail(request=, poll_id='23')
Because the URL patterns are regular expressions, there really is no limit on what you can do with them. And there's no need to add URL cruft such as .php -- unless you have a sick sense of humor, in which case you can do something like this:
(r'^polls/latest\.php$', 'mysite.polls.views.index'),
Note that these regular expressions do not search GET and POST parameters, or the domain name. For example, in a request to http://www.example.com/myapp/, the URLconf will look for myapp/. In a request to http://www.example.com/myapp/?page=3, the URLconf will look for myapp/.
If you need help with regular expressions, see Wikipedia's entry and the Python documentation. Also, the O'Reilly book "Mastering Regular Expressions" by Jeffrey Friedl is fantastic.
Finally, a performance note: these regular expressions are compiled the first time the URLconf module is loaded. They're super fast.
Write your first view
Well, we haven't created any views yet -- we just have the URLconf. But let's make sure Django is following the URLconf properly.Fire up the Django development Web server:
python manage.py runserver
ViewDoesNotExist at /polls/
Tried index in module mysite.polls.views. Error was: 'module'
object has no attribute 'index'
Try "/polls/23/", "/polls/23/results/" and "/polls/23/vote/". The error messages tell you which view Django tried (and failed to find, because you haven't written any views yet).
Time to write the first view. Open the file mysite/polls/views.py and put the following Python code in it:
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the poll index.")
Now lets add a few more views. These views are slightly different, because they take an argument (which, remember, is passed in from whatever was captured by the regular expression in the URLconf):
def detail(request, poll_id):
return HttpResponse("You're looking at poll %s." % poll_id)
def results(request, poll_id):
return HttpResponse("You're looking at the results of poll %s." % poll_id)
def vote(request, poll_id):
return HttpResponse("You're voting on poll %s." % poll_id)
Write views that actually do something
Each view is responsible for doing one of two things: Returning an HttpResponse object containing the content for the requested page, or raising an exception such as Http404. The rest is up to you.Your view can read records from a database, or not. It can use a template system such as Django's -- or a third-party Python template system -- or not. It can generate a PDF file, output XML, create a ZIP file on the fly, anything you want, using whatever Python libraries you want.
All Django wants is that HttpResponse. Or an exception.
Because it's convenient, let's use Django's own database API, which we covered in Tutorial 1. Here's one stab at the index() view, which displays the latest 5 poll questions in the system, separated by commas, according to publication date:
from mysite.polls.models import Poll
from django.http import HttpResponse
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
output = ', '.join([p.question for p in latest_poll_list])
return HttpResponse(output)
from django.template import Context, loader
from mysite.polls.models import Poll
from django.http import HttpResponse
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
t = loader.get_template('polls/index.html')
c = Context({
'latest_poll_list': latest_poll_list,
})
return HttpResponse(t.render(c))
Reload the page. Now you'll see an error:
TemplateDoesNotExist at /polls/
polls/index.html
When you've done that, create a directory polls in your template directory. Within that, create a file called index.html. Note that our loader.get_template('polls/index.html') code from above maps to "[template_directory]/polls/index.html" on the filesystem.
Put the following code in that template:
{% if latest_poll_list %}
{% for poll in latest_poll_list %}
href="/polls/{{ poll.id }}/">{{ poll.question }} {% endfor %}
{% else %}
No polls are available.
{% endif %}
A shortcut: render_to_response()
It's a very common idiom to load a template, fill a context and return an HttpResponse object with the result of the rendered template. Django provides a shortcut. Here's the full index() view, rewritten:from django.shortcuts import render_to_response
from mysite.polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
The render_to_response() function takes a template name as its first argument and a dictionary as its optional second argument. It returns an HttpResponse object of the given template rendered with the given context.
Raising 404
Now, let's tackle the poll detail view -- the page that displays the question for a given poll. Here's the view:from django.http import Http404
# ...
def detail(request, poll_id):
try:
p = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise Http404
return render_to_response('polls/detail.html', {'poll': p})
We'll discuss what you could put in that polls/detail.html template a bit later, but if you'd like to quickly get the above example working, just:
{{ poll }}
A shortcut: get_object_or_404()
It's a very common idiom to use get() and raise Http404 if the object doesn't exist. Django provides a shortcut. Here's the detail() view, rewritten:from django.shortcuts import render_to_response, get_object_or_404
# ...
def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/detail.html', {'poll': p})
Philosophy
Why do we use a helper function get_object_or_404() instead of automatically catching the ObjectDoesNotExist exceptions at a higher level, or having the model API raise Http404 instead of ObjectDoesNotExist?Because that would couple the model layer to the view layer. One of the foremost design goals of Django is to maintain loose coupling.
Write a 404 (page not found) view
When you raise Http404 from within a view, Django will load a special view devoted to handling 404 errors. It finds it by looking for the variable handler404, which is a string in Python dotted syntax -- the same format the normal URLconf callbacks use. A 404 view itself has nothing special: It's just a normal view.You normally won't have to bother with writing 404 views. By default, URLconfs have the following line up top:
from django.conf.urls.defaults import *
Four more things to note about 404 views:
- If DEBUG is set to True (in your settings module) then your 404 view will never be used (and thus the 404.html template will never be rendered) because the traceback will be displayed instead.
- The 404 view is also called if Django doesn't find a match after checking every regular expression in the URLconf.
- If you don't define your own 404 view -- and simply use the default, which is recommended -- you still have one obligation: To create a 404.html template in the root of your template directory. The default 404 view will use that template for all 404 errors.
- If DEBUG is set to False (in your settings module) and if you didn't create a 404.html file, an Http500 is raised instead. So remember to create a 404.html.
Write a 500 (server error) view
Similarly, URLconfs may define a handler500, which points to a view to call in case of server errors. Server errors happen when you have runtime errors in view code.Use the template system
Back to the detail() view for our poll application. Given the context variable poll, here's what the "polls/detail.html" template might look like:{{ poll.question }}
{% for choice in poll.choice_set.all %}
{{ choice.choice }} {% endfor %}
Method-calling happens in the {% for %} loop: poll.choice_set.all is interpreted as the Python code poll.choice_set.all(), which returns an iterable of Choice objects and is suitable for use in the {% for %} tag.
Simplifying the URLconfs
Take some time to play around with the views and template system. As you edit the URLconf, you may notice there's a fair bit of redundancy in it:urlpatterns = patterns('',
(r'^polls/$', 'mysite.polls.views.index'),
(r'^polls/(?P\d+)/$' , 'mysite.polls.views.detail'),
(r'^polls/(?P\d+)/results/$' , 'mysite.polls.views.results'),
(r'^polls/(?P\d+)/vote/$' , 'mysite.polls.views.vote'),
)
Because this is a common case, the URLconf framework provides a shortcut for common prefixes. You can factor out the common prefixes and add them as the first argument to patterns(), like so:
urlpatterns = patterns('mysite.polls.views',
(r'^polls/$', 'index'),
(r'^polls/(?P\d+)/$' , 'detail'),
(r'^polls/(?P\d+)/results/$' , 'results'),
(r'^polls/(?P\d+)/vote/$' , 'vote'),
)
Decoupling the URLconfs
While we're at it, we should take the time to decouple our poll-app URLs from our Django project configuration. Django apps are meant to be pluggable -- that is, each particular app should be transferable to another Django installation with minimal fuss.Our poll app is pretty decoupled at this point, thanks to the strict directory structure that python manage.py startapp created, but one part of it is coupled to the Django settings: The URLconf.
We've been editing the URLs in mysite/urls.py, but the URL design of an app is specific to the app, not to the Django installation -- so let's move the URLs within the app directory.
Copy the file mysite/urls.py to mysite/polls/urls.py. Then, change mysite/urls.py to remove the poll-specific URLs and insert an include():
# ...
urlpatterns = patterns('',
(r'^polls/', include('mysite.polls.urls')),
# ...
Here's what happens if a user goes to "/polls/34/" in this system:
- Django will find the match at '^polls/'
- Then, Django will strip off the matching text ("polls/") and send the remaining text -- "34/" -- to the 'mysite.polls.urls' URLconf for further processing.
urlpatterns = patterns('mysite.polls.views',
(r'^$', 'index'),
(r'^(?P\d+)/$' , 'detail'),
(r'^(?P\d+)/results/$' , 'results'),
(r'^(?P\d+)/vote/$' , 'vote'),
)
No comments:
Post a Comment