Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

5.8 Implementing the Views and URL Configurations to the Rest of the Site

We now have a fundamental understanding of URL configurations and views and have two fully functional webpages using the best tools at our disposal. With these tools, we will now build the rest of the webpages in our site.

5.8.1 Restructuring Our homepage() View

Before we build out new views, it is in our best interest to change our homepage() view to give it a more sensible name and URL path.

Given that it is a list of Tag objects, we should replace the URL pattern so that it matches tag/ as the URL path and provide it with a name, organizer_tag_list, as demonstrated in Example 5.41 in /organizer/urls.py.

Example 5.41: Project Code

organizer/urls.py in 1f86398a5e

 1  from django.conf.urls import url
 2
 3  from .views import tag_detail, tag_list
 4
 5  urlpatterns = [
 6      url(r'^tag/$',
 7          tag_list,
 8          name='organizer_tag_list'),
 9      url(r'^tag/(?P<slug>[\w\-]+)/$',
10          tag_detail,
11          name='organizer_tag_detail'),
12  ]

Note that we use ^ and $ in the URL pattern starting on line 6 to carefully define the start and end of the URL path.

In our /organizer/views.py file, we thus need to rename our homepage() view to tag_list(), as in Example 5.42. We make no other changes.

Example 5.42: Project Code

organizer/views.py in 1f86398a5e

16  def tag_list(request):
17      return render(
18          request,
19          'organizer/tag_list.html',
20          {'tag_list': Tag.objects.all()})

Given our changes, http://127.0.0.1:8000/ is no longer a valid URL. Django notes the result of our changes by displaying the list of valid URL patterns, indicating that we may browse to http://127.0.0.1:8000/tag/ or http://127.0.0.1:8000/tag/<slug>/, such as http://127.0.0.1:8000/tag/mobile/, to display valid pages.

5.8.2 Building a Startup List Page

In /organizer/urls.py, we begin by creating a URL pattern for a startup list page, as shown in Example 5.43. Our new URL pattern will direct requests for URL path startup/ to the function view startup_list().

Example 5.43: Project Code

organizer/urls.py in 69767312bf

 3  from .views import (
 4      startup_list, tag_detail, tag_list)
 .       ...
 6  urlpatterns = [
 7      url(r'^startup/$',
 8          startup_list,
 9          name='organizer_startup_list'),
 .       ...
16  ]

In /organizer/views.py, we may follow the example of our Tag object list view when building one for Startup objects. In Example 5.44, we load and render the template we built for this purpose and pass in all of the Startup objects in the database to the name of the template variable, which we earlier named startup_list.

Example 5.44: Project Code

organizer/views.py in 69767312bf

 4  from .models import Startup, Tag
 .      ...
 7  def startup_list(request):
 8      return render(
 9          request,
10          'organizer/startup_list.html',
11          {'startup_list': Startup.objects.all()})

Remember to add the imports, as shown in Examples 5.43 and 5.44!

5.8.3 Building a Startup Detail Page

As we did for our tag_detail() view, we will now build a startup_detail() view. The function will show a single Startup object, directed to in the URL by the slug field of the model. Our function view thus must take not only a request argument but also a slug argument. In /organizer/views.py, enter the code shown in Example 5.45.

Example 5.45: Project Code

organizer/views.py in bb3aa7eb88

 7  def startup_detail(request, slug):
 8      startup = get_object_or_404(
 9          Startup, slug--iexact=slug)
10      return render(
11          request,
12          'organizer/startup_detail.html',
13          {'startup': startup})

As before, we use the slug value passed by the URL configuration to query the database via the Django-provided get_object_or_404, which will display an HTTP 404 page in the event the slug value passed does not match one in the database. We then use render() to load a template and pass the startup object yielded by our query to the template, to be rendered via the template variable of the same name.

In /organizer/urls.py, we direct Django to our new view by adding the URL pattern shown in Example 5.46.

Example 5.46: Project Code

organizer/urls.py in bb3aa7eb88

 3  from .views import (
 4      startup_detail, startup_list, tag_detail,
 5      tag_list)
 .      ...
 7  urlpatterns = [
 .      ...
11      url(r'^startup/(?P<slug>[\w\-]+)/$',
12          startup_detail,
13          name='organizer_startup_detail'),
 .      ...
20  ]

Note again the ^ and $ characters that define the beginning and end of our URL path and how our use of regular expression named groups allows us to pass the slug portion of the URL directly to our view as a keyword argument. We make sure, as always, to name the URL pattern.

5.8.4 Connecting the URL Configuration to Our Blog App

We’ve created the four display webpages in our organizer app. We will now build two pages in our blog app. To maintain app encapsulation, we must first create an app-specific URL configuration file and then point a URL pattern in the site-wide URL configuration to it.

Start by creating /blog/urls.py and coding the very basic requirements for a URL configuration. This will yield the code shown in Example 5.47.

Example 5.47: Project Code

blog/urls.py in 02dabec093

1  urlpatterns = [
2  ]

In /suorganizer/urls.py we can direct Django to our blog app URL configuration thanks to include(), as shown in Example 5.48.

Example 5.48: Project Code

suorganizer/urls.py in 02dabec093

19  from blog import urls as blog_urls
 .      ...
22  urlpatterns = [
 .      ...
24      url(r'^blog/', include(blog_urls)),
 .      ...
26  ]

Remember that the full URL configuration is actually a tree. If a URL pattern points to another URL configuration, Django will pass the next URL configuration a truncated version of the URL path. We can thus continue to use the ^ regular expression character to match the beginning of strings, but we cannot use the $ to match the end of a string. When the user requests the blog post webpage, he or she will request /blog/2013/1/django-training/. Django will remove the root slash and match the URL path in the request to the URL pattern above, as the regular expression r'^blog/' matches the path. Django will use the regular expression pattern r'^blog/' to truncate the path to 2013/1/django-training/. This is the path it will forward to the blog URL configuration and is what we want our post detail view to match.

Before we create a blog post detail view, let us first program a list view for posts.

5.8.5 Building a Post List Page

With our blog app connected via URL configuration, we can now add URL patterns. Let’s start with a list of blog posts.

In /blog/views.py, our function view is straightforward, as you can see in Example 5.49.

Example 5.49: Project Code

blog/views.py in 928c982c03

 1  from django.shortcuts import render
 2
 3  from .models import Post
 4
 5
 6  def post_list(request):
 7      return render(
 8          request,
 9          'blog/post_list.html',
10          {'post_list': Post.objects.all()})

We wish to list our blog posts at /blog/. However, this is already the URL path matched by our call to include in suorganizer/urls.py. When a user requests /blog/, Django will remove the root /, and match the URL pattern we just built. Django will then use r'^blog/' to truncate the path from blog/ to the empty string (i.e., nothing). We are thus seeking to display a list of blog posts when Django forwards our blog app the empty string. In Example 5.50, we match the empty string with the regular expression pattern r'^$'.

Example 5.50: Project Code

blog/urls.py in 928c982c03

1  from django.conf.urls import url
2
3  from .views import post_list
4
5  urlpatterns = [
6      url(r'^$',
7          post_list,
8          name='blog_post_list'),
9  ]

5.8.6 Building a Post Detail Page

The final view left to program is our detail view of a single Post object. Programming the view and URL pattern for this view is a little bit trickier than our other views: the URL for each Post object is based not only on the slug but also on the date of the object, making the regular expression pattern and query to the database a little more complicated. Recall that we are enforcing this behavior in our Post model via the unique_for_month attribute on the slug.

Take http://site.django-unleashed.com/blog/2013/1/django-training/ as an example. After include() in our root URL configuration truncates blog/ from the URL path, our blog app URL configuration will receive 2013/1/django-training/. Our regular expression pattern must match a year, month, and slug and pass each one as a value to our view.

The year is four digits, and our named group is thus (?P<year>\d{4}). A month may have one or two digits, so our named group is (?P<month>\d{1,2}). Finally, and as before, our slug is any set of alphanumeric, underscore, or dash characters with length greater than one, so we write our named group as (?P<slug>[\w\-]+). We separate each part of the URL path with a / and wrap the string with ^ and $ to signify the beginning and end of the URL path to match. The string containing our regular expression is thus r'^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<slug>[\w\-]+)/$'.

To direct Django to a view in /blog/views.py, we may write the call in Example 5.51 to url().

Example 5.51: Project Code

blog/urls.py in cb5dd59383

 3  from .views import post_detail, post_list
 .      ...
 5  urlpatterns = [
 .      ...
 9      url(r'^(?P<year>\d{4})/'
10          r'(?P<month>\d{1,2})/'
11          r'(?P<slug>[\w\-]+)/$',
12          post_detail,
13          name='blog_post_detail'),
14  ]

Our function view will thus accept four parameters: request, year, month, and slug. In Example 5.52, in /blog/views.py, start by changing the import to include get_object_or_404, which we will need for our detail page.

Example 5.52: Project Code

blog/views.py in cb5dd59383

1  from django.shortcuts import (
2      get_object_or_404, render)

We must now build a query for the database. Our Post model contains a pub_date field, which we could compare to a datetime.date, but we don’t have the necessary information to build one (we lack the day). For the occasion, Django provides DateField and DateTimeField objects with special field lookups that break each field down by its constituents, allowing us to query pub_date_year and pub_date_month to filter results. In the case of our example URL, http://site.django-unleashed.com/blog/2013/1/django-training/, this functionality allows us to write the query shown in Example 5.53.

Example 5.53: Python Code

Post.objects
    .filter(pub--date--year=2014)
    .filter(pub--date--month=11)
    .get(slug--iexact='django-training')

While the query to our Post model manager will work, it is more desirable to use the get_object_or_404 to minimize developer-written code. Recall that get_object_or_404 wants a model class and a query string as parameters. Django does not limit the number of query strings passed to get_object_or_404, allowing developers to pass as many as necessary. Given n arguments, the first n-1 will call filter(), while the nth will result in a call to get(). Practically, this means Django will re-create the query in Example 5.53 for us exactly, with the call shown in Example 5.54.

Example 5.54: Project Code

blog/views.py in cb5dd59383

 8     post = get_object_or_404(
 9         Post,
10         pub_date--year=year,
11         pub_date--month=month,
12         slug=slug)

The rest of our view is exactly like any other. The view passes the HttpRequest object, a dictionary, and a string to render(). The render() shortcut uses the HttpRequest object and the dictionary to build a RequestContext object. The string passes a path to the template file, allowing render() to load the template and render the template with the RequestContext object. The shortcut then returns an HttpResponse object to the view, which the view passes on to Django. Our final view is thus shown in Example 5.55.

Example 5.55: Project Code

blog/views.py in cb5dd59383

 7  def post_detail(request, year, month, slug):
 8      post = get_object_or_404(
 9          Post,
10          pub_date--year=year,
11          pub_date--month=month,
12          slug=slug)
13      return render(
14          request,
15          'blog/post_detail.html',
16          {'post': post})
  • + Share This
  • 🔖 Save To Your Account