Views and URLconfs in Django

In the previous chapters, we have learned how to set up a Django project and run the development server. In this chapter, we will learn the basics of creating dynamic web pages in Django.

Creating the first View

Let’s start simple. In this section, we will create a web page that outputs "Hello Django". To do this open located in the blog app (i.e TGDB/django_project/blog) in your favorite text editor.

At this point, should look like this:


Delete everything and enter the following code.


We have just created a simple view function.

So what’s a view function?

A function whose job is to accept a request and return a proper response.

Let’s step through the code we have added one line at a time.

  1. In line 1, we are importing HttpResponse class from django.http module.
  2. In lines 4-5, we are defining index() function which returns an instance of HttpResponse object.

The important thing to remember about the view function is that every view function must accept a parameter called request by convention, which is an object of type HttpRequest. Certainly, you can call this parameter anything you want, however, it is highly recommended not to change it. The HttpRequest object contains the information about the current web request that has triggered this view.

Every view function must return a HttpResponse object. To create a HttpResponse object, simply pass a string representing the content of the page to HttpResponse().

Now we have created a simple view. To call this view you must create a URL pattern in the URL Configuration or URLconf in short. You can think of URLconf as a table of contents for Django powered web app. In other words, URLconf is a mapping between URLs and view functions that should be called for those URLs. It is Django’s way of saying for this URL call this view function and for that URL call that view function and so on.

We create URL pattern using url() function. It accepts two arguments, a regular expression to match the URL and name of the view function to call for this URL.

Let’s create a URL pattern. Open located in the Django Project Configuration directory (i.e
TGDB/django_project/django_project). This file is also known as sitewide The contents of file should look like this.


Note: Comments are removed from the above code snippet to save space.

To tell the existence of index() view function in you need to do two things:

  1. Add from blog import views towards the end of the import list.
  2. Create a new URL pattern by adding the following line at the beginning of the urlpatterns list.

The contents of the file should now look like this:


Start the Django development server if not already running using python runserver command and visit You should see a page like this:

django first view

The first parameter to url() is a regular expression string and the second is the name of the view function. The regular expression r'^$' matches nothing. In other words, r'^$' refers to the root of the website. If our domain is then a request to will call index() view function. When a user requests Django uses urlpatterns list to figure out which method to call. When it finds the URL pattern that matches, it calls the view function associated with that pattern. If a matching pattern is not found, an HTTP 404 error is returned.

Don’t forget what Django calls view is actually a controller.

The url() function accepts many other optional parameters, one such parameter is name keyword argument. The name keyword argument allows us to give a unique name to the URL pattern. So why should we give names to our URL patterns? Defining a name allows us to create URLs automatically in our templates and views. We will see how it’s done in the lesson Creating URLs in Django . For now, let’s give a name to our newly created URL pattern.


Django 404 Errors

Our URLconf at this point contains only two URL patterns – one was provided by Django and the one which we wrote ourself. So what would happen if you request a different URL? Open your browser and try visiting If the requested URL doesn’t match to any of the URL patterns in URLconf then Django throws a 404 error. As the requested URL is not defined in the URLconf, Django throws an HTTP 404 not found error. Here is how it looks:

django 404 error

The important thing to note about this page is that it gives way lot more information than it is required. Notice that it exactly tells what URL patterns Django tried from which URLconf before throwing HTTP 404 error. Sure, this is sensitive information and should be disclosed only to the people involved in the development of the web app.

So, If this information is sensitive then why Django is revealing all this in the first place?

Because by default Django project installed with DEBUG set to True. To view this setting open in Django project configuration directory located at TGDB/django_project/django_project.


Notice that DEBUG is set to True.

To turn off the debug mode set the value of DEBUG to False. When debug mode is off Django outputs a different HTTP 404 response without any sensitive information. As we are currently in the development phase keep the DEBUG setting to True.

Mapping URLs the right way

Right now, we only have one application namely blog in our Django project. Generally, a project consists of at least 3-4 apps. If we keep writing URLconf for every app in the sitewide file soon it would become a mess. So instead of mappings the URLs directly to project’s, we can make our application modular by creating for every application, that way we can manage URLs much more efficiently and easily. To do so, first create file inside the blog app and add the following code to it.


In line 1 and 2, we are importing necessary function and module. In line 4, we are creating URLconf for the blog app.

The next step is to inform the Django project about the URLconf of the blog app. To do so, modify the sitewide as follows:


The include() function tells sitewide file about the existence of in the blog app. The important thing to note here is that in the regular expression r'^blog/' doesn’t have a trailing $ character instead it has a trailing slash /. This is done so because whenever Django encounters include() function, it chops off whatever the part of the URL matches up to that point and sends the remaining part of the URL to the included URLconf for further processing.

Open your browser and navigate to Django will greet you with "Hello Django" response.

Digging deep into the URLs

Let’s see what happens when you request a page.

  1. When you request a page the first thing Django does is to remove the host portion of the URL, for example: in the URL the host portion is
  2. Then, Django reads value of variable ROOT_URLCONF from Django project’s file. So what’s the role of ROOT_URLCONF?ROOT_URLCONF contains the URLconf which must be loaded first. It is also known as root URLconf or sitewide URLconf. In our case it points to located in TGDB/django_project/django_project.
  3.  After reading ROOT_URLCONF, Django checks each URL pattern one by one in the root URLconf with the requested URL until a match is found. If a pattern is not found a 404 error is returned.
  4. On the other hand, If a pattern is found then it calls the associated view function. If the second parameter to the url() function includes a call to include() function then Django chops off whatever the part of the URL matches up to that point and sends the remaining part of the URL to the included URLconf for further processing.

Consider the following example:

Let’s say the requested URL is, the first thing Django does is to remove the host portion of the URL. After stripping host portion becomes /time/. The string /time/ is then checked against each URL pattern one by one, until a match is found. If a match is found corresponding view function is called. Otherwise, an HTTP 404 error is returned.

Outputting Dynamic Data

The view function we created in the above section was very simple, nonetheless, it introduced you to some basics concepts like view functions, URL patterns and how Django processes the URLs behind the scene. In our next view, we will output some dynamic content. Let’s create a simple web page to output current date and time. If you have done some Python programming then you may already know that Python has datetime module for working with date and time. Here is a quick refresher on how to use it:

It is important to note that above the snippet is pure Python and it has nothing to do with Django. To return current date and time we first have to create a new view. Open in the blog app and add a new view function called today_is() below index() view function as follows:


Let’s step through the changes we have made in the file:

  1. In line 2, we have added an import statement to import datetime module, so that we can calculate current date and time.
  2. In lines 9-12, we have defined today_is() function. In line 10, we are calculating current date and time by calling now() method and assigning the result to the now variable. In line 11, we are creating an HTML response using string object’s format() method. The {0} inside the string is just a placeholder for the current date and time and will be replaced by the value of the variable now. It is important to note that the variable now represents a datetime.datetime object not a regular string but when the value of now is printed inside the string in place of {0}, the __str__() method of datatime.datetime object converts datatime.datetime object to a string. Finally, the view returns an HttpResponse() object containing the generated response.

With view function in place, let’s create a new URL pattern to call this view. Open blog app’s and add the following URL pattern to call today_is() view function as follows:

We have added a new URL pattern to map /time/ URL to the today_is() view function. At this point, you are probably getting the hang of this. Start the server if not already running and visit If everything went fine Django will greet you with current date and time.

current date and time

Views Limitation

So far we have been able to pull off a basic app using just using View part of the MTV pattern. But still our app is severely limited because of following reasons:

  1. 1. We are hardcoding HTML code inside our views. At a later date, if we want to modify our HTML it would be very painful to go through each view one by one to modify the page. Django comes bundled with a powerful templating system which allows us to create complex HTML pages easily instead of hardcoding them inside views. If we keep hardcoding HTML directly in the view we wouldn’t be able to use loops or conditional statements that Django templating system provides inside our HTML (we will see how to use them in Template tags in Django lesson).
  2. In the real world, a page consists of many dynamic components. Embedding dynamic content in a large page using format() method is very error-prone and tedious.
  3.  At this point, we haven’t yet introduced database into the scene because it would create more mess.

In the upcoming chapters, you will see how using Models and Templates in conjunction with Views helps us to greatly simplify all the above-mentioned issues.

Note: To checkout this version of the repository type git checkout 5a.

13 thoughts on “Views and URLconfs in Django

  1. It is great great greater! It is best best better! Excellent tutorial which I tried hard to find out by lost more more times. Thanks TUTOR.

  2. Great tutorial! Thanks for providing this. Just noting, this page would be compatible with later versions of Django if you mentioned that the root url path for index should be empty, as in ”, not ‘^$’ in Django 2, and when DEBUG is set to False, ALLOWED_HOSTS must be changed. ‘*’ is an acceptable value in development.

  3. Shouldn’t ‘’ be ‘’. It worked for me to display time

    • I cannot get to my djangpo files on Terminal. It is hung with message (Process completed). I tried Force Quit, but that didn’t work. Nor did Restart or Shutdown get rid of (process complete). I believe i was in virtual env and hit the wrong key to exit. I can show you my files in Finder but I am dead in the water without Terminal available.

      • What commands are you using? Try creating a new virtual environment. And if possible share your code.

    • Since the Terminal is hung, I cannot enter any command. However if i enter /bin/sh in Run Command, I get a new window where I can enter commands.. I think the message (Process completed) came from exiting virtualenv. I am thinking of changing from bash and sh to zsh to avoid this problem which may be a problem with bash or virtualenv. I contacted Apple but they could not help because Virtualenv is third party software. Some developers recommend adding code to .bashrc.

      • I using bash myself and I never experienced any such issue. If you are still facing the problem, try creating the project in an online IDE (like cloud9) or on a real web server (like digitalocean ).

  4. your explanation is lucid and to the point. Why don’t you add a small tutorial on Regular Expression – a tiny language itself ?

Leave a Comment

%d bloggers like this: