Writing your first Django app, part 3

This tutorial begins where Tutorial 2 left off. We’recontinuing the Web-poll application and will focus on creating the publicinterface – “views.”

Overview

A view is a “type” of Web page in your Django application that generally servesa specific function and has a specific template. For example, in a blogapplication, 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 thegiven year.
  • Month-based archive page – displays all days with entries in thegiven month.
  • Day-based archive page – displays all entries in the given day.
  • Comment action – handles posting comments to a given entry.In our poll application, we’ll have the following four views:

  • Question “index” page – displays the latest few questions.

  • Question “detail” page – displays a question text, with no results butwith a form to vote.
  • Question “results” page – displays results for a particular question.
  • Vote action – handles voting for a particular choice in a particularquestion.In Django, web pages and other content are delivered by views. Each view isrepresented by a Python function (or method, in the case of class-based views).Django will choose a view by examining the URL that’s requested (to be precise,the part of the URL after the domain name).

Now in your time on the web you may have come across such beauties as“ME2/Sites/dirmod.asp?sid=&type=gen&mod=Core+Pages&gid=A6CD4967199A42D9B65B1B”.You will be pleased to know that Django allows us much more elegantURL patterns than that.

A URL pattern is the general form of a URL - for example:/newsarchive/<year>/<month>/.

To get from a URL to a view, Django uses what are known as ‘URLconfs’. AURLconf maps URL patterns to views.

This tutorial provides basic instruction in the use of URLconfs, and you canrefer to URL dispatcher for more information.

Writing more views

Now let’s add a few more views to polls/views.py. These views areslightly different, because they take an argument:

polls/views.py

  1. def detail(request, question_id):
  2. return HttpResponse("You're looking at question %s." % question_id)
  3.  
  4. def results(request, question_id):
  5. response = "You're looking at the results of question %s."
  6. return HttpResponse(response % question_id)
  7.  
  8. def vote(request, question_id):
  9. return HttpResponse("You're voting on question %s." % question_id)

Wire these new views into the polls.urls module by adding the followingpath() calls:

polls/urls.py

  1. from django.urls import path
  2.  
  3. from . import views
  4.  
  5. urlpatterns = [
  6. # ex: /polls/
  7. path('', views.index, name='index'),
  8. # ex: /polls/5/
  9. path('<int:question_id>/', views.detail, name='detail'),
  10. # ex: /polls/5/results/
  11. path('<int:question_id>/results/', views.results, name='results'),
  12. # ex: /polls/5/vote/
  13. path('<int:question_id>/vote/', views.vote, name='vote'),
  14. ]

Take a look in your browser, at “/polls/34/”. It’ll run the detail()method and display whatever ID you provide in the URL. Try“/polls/34/results/” and “/polls/34/vote/” too – these will display theplaceholder results and voting pages.

When somebody requests a page from your website – say, “/polls/34/”, Djangowill load the mysite.urls Python module because it’s pointed to by theROOT_URLCONF setting. It finds the variable named urlpatternsand traverses the patterns in order. After finding the match at 'polls/',it strips off the matching text ("polls/") and sends the remaining text –"34/" – to the ‘polls.urls’ URLconf for further processing. There itmatches '<int:question_id>/', resulting in a call to the detail() viewlike so:

  1. detail(request=<HttpRequest object>, question_id=34)

The question_id=34 part comes from <int:question_id>. Using anglebrackets “captures” part of the URL and sends it as a keyword argument to theview function. The :question_id> part of the string defines the name thatwill be used to identify the matched pattern, and the <int: part is aconverter that determines what patterns should match this part of the URL path.

There’s no need to add URL cruft such as .html – unless you want to, inwhich case you can do something like this:

  1. path('polls/latest.html', views.index),

But, don’t do that. It’s silly.

Write views that actually do something

Each view is responsible for doing one of two things: returning anHttpResponse object containing the content for therequested page, or raising an exception such as Http404. Therest is up to you.

Your view can read records from a database, or not. It can use a templatesystem 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, anythingyou 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 coveredin Tutorial 2. Here’s one stab at a new index()view, which displays the latest 5 poll questions in the system, separated bycommas, according to publication date:

polls/views.py

  1. from django.http import HttpResponse
  2.  
  3. from .models import Question
  4.  
  5.  
  6. def index(request):
  7. latest_question_list = Question.objects.order_by('-pub_date')[:5]
  8. output = ', '.join([q.question_text for q in latest_question_list])
  9. return HttpResponse(output)
  10.  
  11. # Leave the rest of the views (detail, results, vote) unchanged

There’s a problem here, though: the page’s design is hard-coded in the view. Ifyou want to change the way the page looks, you’ll have to edit this Python code.So let’s use Django’s template system to separate the design from Python bycreating a template that the view can use.

First, create a directory called templates in your polls directory.Django will look for templates in there.

Your project’s TEMPLATES setting describes how Django will load andrender templates. The default settings file configures a DjangoTemplatesbackend whose APP_DIRS option is set toTrue. By convention DjangoTemplates looks for a “templates”subdirectory in each of the INSTALLED_APPS.

Within the templates directory you have just created, create anotherdirectory called polls, and within that create a file calledindex.html. In other words, your template should be atpolls/templates/polls/index.html. Because of how the app_directoriestemplate loader works as described above, you can refer to this template withinDjango as polls/index.html.

Template namespacing

Now we might be able to get away with putting our templates directly inpolls/templates (rather than creating another polls subdirectory),but it would actually be a bad idea. Django will choose the first templateit finds whose name matches, and if you had a template with the same namein a different application, Django would be unable to distinguish betweenthem. We need to be able to point Django at the right one, and the bestway to ensure this is by namespacing them. That is, by putting thosetemplates inside another directory named for the application itself.

Put the following code in that template:

polls/templates/polls/index.html

  1. {% if latest_question_list %}
  2. <ul>
  3. {% for question in latest_question_list %}
  4. <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
  5. {% endfor %}
  6. </ul>
  7. {% else %}
  8. <p>No polls are available.</p>
  9. {% endif %}

Now let’s update our index view in polls/views.py to use the template:

polls/views.py

  1. from django.http import HttpResponse
  2. from django.template import loader
  3.  
  4. from .models import Question
  5.  
  6.  
  7. def index(request):
  8. latest_question_list = Question.objects.order_by('-pub_date')[:5]
  9. template = loader.get_template('polls/index.html')
  10. context = {
  11. 'latest_question_list': latest_question_list,
  12. }
  13. return HttpResponse(template.render(context, request))

That code loads the template called polls/index.html and passes it acontext. The context is a dictionary mapping template variable names to Pythonobjects.

Load the page by pointing your browser at “/polls/”, and you should see abulleted-list containing the “What’s up” question from Tutorial 2. The link points to the question’s detail page.

A shortcut: render()

It’s a very common idiom to load a template, fill a context and return anHttpResponse object with the result of the renderedtemplate. Django provides a shortcut. Here’s the full index() view,rewritten:

polls/views.py

  1. from django.shortcuts import render
  2.  
  3. from .models import Question
  4.  
  5.  
  6. def index(request):
  7. latest_question_list = Question.objects.order_by('-pub_date')[:5]
  8. context = {'latest_question_list': latest_question_list}
  9. return render(request, 'polls/index.html', context)

Note that once we’ve done this in all these views, we no longer need to importloader and HttpResponse (you’llwant to keep HttpResponse if you still have the stub methods for detail,results, and vote).

The render() function takes the request object as itsfirst argument, a template name as its second argument and a dictionary as itsoptional third argument. It returns an HttpResponseobject of the given template rendered with the given context.

Raising a 404 error

Now, let’s tackle the question detail view – the page that displays the question textfor a given poll. Here’s the view:

polls/views.py

  1. from django.http import Http404
  2. from django.shortcuts import render
  3.  
  4. from .models import Question
  5. # ...
  6. def detail(request, question_id):
  7. try:
  8. question = Question.objects.get(pk=question_id)
  9. except Question.DoesNotExist:
  10. raise Http404("Question does not exist")
  11. return render(request, 'polls/detail.html', {'question': question})

The new concept here: The view raises the Http404 exceptionif a question with the requested ID doesn’t exist.

We’ll discuss what you could put in that polls/detail.html template a bitlater, but if you’d like to quickly get the above example working, a filecontaining just:

polls/templates/polls/detail.html

  1. {{ question }}

will get you started for now.

A shortcut: get_object_or_404()

It’s a very common idiom to use get()and raise Http404 if the object doesn’t exist. Djangoprovides a shortcut. Here’s the detail() view, rewritten:

polls/views.py

  1. from django.shortcuts import get_object_or_404, render
  2.  
  3. from .models import Question
  4. # ...
  5. def detail(request, question_id):
  6. question = get_object_or_404(Question, pk=question_id)
  7. return render(request, 'polls/detail.html', {'question': question})

The get_object_or_404() function takes a Django modelas its first argument and an arbitrary number of keyword arguments, which itpasses to the get() function of themodel’s manager. It raises Http404 if the object doesn’texist.

Philosophy

Why do we use a helper function get_object_or_404()instead of automatically catching theObjectDoesNotExist exceptions at a higherlevel, or having the model API raise Http404 instead ofObjectDoesNotExist?

Because that would couple the model layer to the view layer. One of theforemost design goals of Django is to maintain loose coupling. Somecontrolled coupling is introduced in the django.shortcuts module.

There’s also a get_list_or_404() function, which worksjust as get_object_or_404() – except usingfilter() instead ofget(). It raisesHttp404 if the list is empty.

Use the template system

Back to the detail() view for our poll application. Given the contextvariable question, here’s what the polls/detail.html template might looklike:

polls/templates/polls/detail.html

  1. <h1>{{ question.question_text }}</h1>
  2. <ul>
  3. {% for choice in question.choice_set.all %}
  4. <li>{{ choice.choice_text }}</li>
  5. {% endfor %}
  6. </ul>

The template system uses dot-lookup syntax to access variable attributes. Inthe example of {{ question.question_text }}, first Django does a dictionary lookupon the object question. Failing that, it tries an attribute lookup – whichworks, in this case. If attribute lookup had failed, it would’ve tried alist-index lookup.

Method-calling happens in the {% for %} loop:question.choice_set.all is interpreted as the Python codequestion.choice_set.all(), which returns an iterable of Choice objects and issuitable for use in the {% for %} tag.

See the template guide for more about templates.

Removing hardcoded URLs in templates

Remember, when we wrote the link to a question in the polls/index.htmltemplate, the link was partially hardcoded like this:

  1. <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>

The problem with this hardcoded, tightly-coupled approach is that it becomeschallenging to change URLs on projects with a lot of templates. However, sinceyou defined the name argument in the path() functions inthe polls.urls module, you can remove a reliance on specific URL pathsdefined in your url configurations by using the {% url %} template tag:

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

The way this works is by looking up the URL definition as specified in thepolls.urls module. You can see exactly where the URL name of ‘detail’ isdefined below:

  1. ...
  2. # the 'name' value as called by the {% url %} template tag
  3. path('<int:question_id>/', views.detail, name='detail'),
  4. ...

If you want to change the URL of the polls detail view to something else,perhaps to something like polls/specifics/12/ instead of doing it in thetemplate (or templates) you would change it in polls/urls.py:

  1. ...
  2. # added the word 'specifics'
  3. path('specifics/<int:question_id>/', views.detail, name='detail'),
  4. ...

Namespacing URL names

The tutorial project has just one app, polls. In real Django projects,there might be five, ten, twenty apps or more. How does Django differentiatethe URL names between them? For example, the polls app has a detailview, and so might an app on the same project that is for a blog. How does onemake it so that Django knows which app view to create for a url when using the{% url %} template tag?

The answer is to add namespaces to your URLconf. In the polls/urls.pyfile, go ahead and add an app_name to set the application namespace:

polls/urls.py

  1. from django.urls import path
  2.  
  3. from . import views
  4.  
  5. app_name = 'polls'
  6. urlpatterns = [
  7. path('', views.index, name='index'),
  8. path('<int:question_id>/', views.detail, name='detail'),
  9. path('<int:question_id>/results/', views.results, name='results'),
  10. path('<int:question_id>/vote/', views.vote, name='vote'),
  11. ]

Now change your polls/index.html template from:

polls/templates/polls/index.html

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

to point at the namespaced detail view:

polls/templates/polls/index.html

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

When you’re comfortable with writing views, read part 4 of this tutorial to learn the basics about form processing and genericviews.