django tutorial

Views and URLconfs 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 views.py located in the djangobin app (i.e myapp/django_project/myapp) in your favorite text editor. At this point, views.py should look like this:

myapp/django_project/myapp/views.py

from django.shortcuts import render
 
# Create your views here.

Delete everything and enter the following code.

myapp/django_project/myapp/views.py

from django.shortcuts import HttpResponse
 
 
def index(request):
    return HttpResponse("<p>Hello Django</p>")

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.shortcuts module.
  2. In lines 4-5, we define the index() function which returns an instance of
    HttpResponse object.

Every view function takes an argument called request, which is an object of type HttpRequest. The HttpRequest object contains the information about the current web request that has triggered this view.

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

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 urls.py file located in the Django project configuration directory (i.e myapp/django_project/django_project). This file is also known as site-wide urls.py. The contents of urls.py file should look like this.

myapp/django_project/django_project/urls.py

from django.contrib import admin
from django.urls import path
 
urlpatterns = [
    path('admin/', admin.site.urls),
]

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

To bind the index() view function to a URL pattern we need to do two things:

  1. Add from myapp 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.
path('', views.index),

The contents of the site-wide urls.py file should now look like this:

myapp/django_project/django_project/urls.py

from django.contrib import admin
from django.urls import path
from myapp import views
 
urlpatterns = [
    path('', views.index),
    path('admin/', admin.site.urls),
]

Start the Django development server if not already running using ./manage.py runserver command and visit http://127.0.0.1:8000/. You should see a page like this:

hello_django

The first parameter passed to the path() function is a regular expression string and the second is the name of the view function. The regular expression ' ' matches nothing. In other words, ' ' refers to the root of the website. If our domain is http://kwikl3arn.com/ then a request to http://kwikl3arn.com/ will call index() view function. When a user requests http://kwikl3arn.com/ 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 path() 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.

myapp/django_project/django_project/urls.py

from django.contrib import admin
from django.urls import path
from myapp import views
 
urlpatterns = [
    path('', views.index, name='index'),
    path('admin/', admin.site.urls),
]

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 http://127.0.0.1:8000/django/.

If the requested URL doesn’t match to any of the existing URL patterns in URLconf then Django throws a 404 error. As the requested URL is not defined in the URLconf, Django will throw an HTTP 404 not found error. Here is how it looks:

django_2

The important point to note about this page is that it gives way lot information than it is required. Notice that it exactly tells what URL patterns Django tried from which URLconf before throwing an 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 mode set to True. To view this setting open settings.py in Django project configuration directory located at myapp/django_project/django_project.

myapp/django_project/django_project/settings.py

#...
 
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#=15=zv^cmq2se-d=@#qp8f1ggbbto=235pz=we723*rt9is_$&hup)'
 
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
 
ALLOWED_HOSTS = []
 
#...

To turn off the debug mode set the value of DEBUG to False. When debug mode is off Django outputs a generic 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 named myapp in our Django project. Generally, a project consists of at least 3-4 apps. If we keep writing URLconf for every app in the site-wide urls.py file soon it would become a mess. So instead of mappings the URLs directly to site-wide urls.py, we can make our application modular by creating urls.py for every application, that way we can manage URLs much more efficiently and easily. To do so, first create urls.py file inside the myapp app and add the following code to it.

myapp/django_project/myapp/urls.py

from django.urls import path
from . import views
 
urlpatterns = [
    path('', views.index, name='index'),
]

Above first two  lines we are importing necessary function and module. In line 4, we are creating URLconf for the myapp app.

The next step is to inform the Django project about the URLconf of the myapp app. To do so, modify the site-wide urls.py as follows:

myapp/django_project/django_project/urls.py

from django.contrib import admin
from django.urls import path,include
 
urlpatterns = [
    path('index/', include('myapp.urls')),
    path('admin/', admin.site.urls),
]

The include() function tells site-wide urls.py file about the existence of urls.py in the myapp app. The important thing to note here is that in the regular expression 'index/' 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.

However, we want to to display hello world at the root URL http://127.0.0.1:8000/ instead of http://127.0.0.1:8000/index/, to do so, replace the regular expression 'index/' with ''.

myapp/django_project/django_project/urls.py

from django.contrib import admin
from django.urls import path,include
 
urlpatterns = [
    path('', include('myapp.urls')),
    path('admin/', admin.site.urls),
]

Open your browser and navigate to http://127.0.0.1:8000/. 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 http://kwikl3arn.com/editor/ the host portion is kwikl3arn.com.

2. Then, Django reads the value of variable ROOT_URLCONF from Django project’s settings.py file. So what’s the role of ROOT_URLCONF?The ROOT_URLCONF contains the URLconf which must be loaded first. It is also known as root URLconf or site-wide URLconf. In our case it points to urls.py located in myapp/django_project/django_project directory.

myapp/django_project/django_project/settings.py

#...
 
ROOT_URLCONF = 'django_project.urls'
 
#...

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 Django calls the associated view function. If the second parameter to the path() 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.

Here is an example:

Let’s say the requested URL is http://example.com/time/, the first thing Django does is to remove the host portion of the URL. After stripping host portion http://example.com/time/ 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 scenes. 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:

>>>
>>> import datetime
>>>
>>> current_datetime = datetime.datetime.now()
>>>
>>> current_datetime
datetime.datetime(2019, 11, 30, 12, 59, 42, 135163)
>>>
>>> print(current_datetime)
2019-11-30 12:59:42.135163
>>>

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 views.py in the djangobin app and add a new view function called today_is() below the index() view function as follows:

myapp/django_project/myapp/views.py

from django.http import HttpResponse
import datetime
 
 
def index(request):
    return HttpResponse("<p>Hello Django</p>")
 
 
def today_is(request):
    now = datetime.datetime.now()
    html = "<html><body>Current date and time: {0}</body></html>".format(now)
    return HttpResponse(html)

Let’s step through the changes we have made in the views.py 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 djangobin app’s urls.py and add the following URL pattern to call today_is() view function as follows:

myapp/django_project/myapp/urls.py

from django.urls import path
from myapp import views
 
urlpatterns = [
    path('time/', views.today_is, name='time'),
    path('', views.index, name='index'),
]

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


Creating Dynamic URLs

Dynamic URL is a URL which contains one or more variable part that influences the output of a webpage. So far we have created only static URLs.

Let’s create another view to display user profile. In the views.py file add profile() view function as follows:

myapp/django_project/myapp/views.py

#...
def today_is(request):
    #...
 
 
def profile(request):
    return HttpResponse("<p>Profile page of user</p>")