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
 3  from .views import tag_detail, tag_list
 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, 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 or<slug>/, such as, 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
 3  from .models import Post
 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
3  from .views import post_list
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


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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020