In this tutorial, we will be looking a little more closely at how Routing works in Django. Any web application needs to look at incoming Http requests and decide what to do with that request. Most times, the application will gather some relevant data, package it up in an Http response, and send it back to the browser. In Django, this process is handled by two files. The first is urls.py, and the second is views.py. The urls.py file is where we can set up URL to View function mappings, and the views.py file is where we can set up functions to trigger when a particular route is visited.
Create A Django Project
To get started looking at Django URLs and Views, we fist need a Django project to get started with. With Python and Django already installed on our system, all we need to do is navigate to a directory of our choice and enter the command django-admin startproject djangoblog.
python $django-admin startproject djangoblog
We can use PyCharm to open our new project like so.
When you first create a Django project, it creates an outer folder name and an inner folder with the same name. It might seem a little confusing at first. Understanding that a Django project is made of individual apps will help clear this up. The outer folder name is the name of the Django project itself. The inner folder name is the base app for the project. That inner root app contains the familiar files of __init__.py, asgi.py, settings.py, urls.py, and wsgi.py.
In the terminal, we’ll want to cd into the project folder and list the contents. We should see the manage.py file and the inner djangoblog app folder as well.
Django URLs and Views
The first thing we need to understand is how URLs and Views work together in Django.
When a web request is made to a Django application, it is the job of the urls.py file to determine what to do with that request. This is what is known as routing in a web application. So you might have URLs set up in your project like
/about-us and so on. Each of those routes will trigger a different function in the views.py file. Each different function will perform a different operation depending on the route the user has chosen via the web browser.
Adding A New Route
Let’s go ahead and open the urls.py file that is in the root app folder. We have removed the comments so that we can simply see what beginning code we are starting with.
We want to add a route for an about page for example. Here is the highlighted code to do that.
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('about/', views.about) ]
What the code above is saying is that when someone visits the
/about page in a web browser, the urls.py file will look in the views.py file and trigger the
about() function. We don’t yet have that code in place yet, so let’s create it now.
Once the new views.py file is created in the inner djangoblog folder, we can set up our function.
from django.http import HttpResponse def about(request): return HttpResponse('<h1>About!</h1>')
If we did everything correctly, we should be able to now start up the python local development server and test this out. Below we run the python manage.py runserver command to start the server.
djangoblog $python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. February 13, 2020 - 12:14:35 Django version 3.0.3, using settings 'djangoblog.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK.
Now we can run the browser and visit http://127.0.0.1:8000/about/ to see the result.
Not sexy, but the URL to view mapping is working! A request is made to
/about, the urls.py file is configured to trigger the about() function in views.py, and that function returns a simple HttpResponse object with the string ‘About!’.
Creating A Second URL / View Mapping
This process can continue and you can add as many different routes and view functions as you need to provide whatever result you are looking for. We don’t yet have a home page, so we can add that now. This time, we’ll define the home() function in our views.py file, and once that is in place we’ll adjust the urls.py file to link the two together.
So once again, we’ll just define a simple function in views.py. This time the function is named home(). It’s only job is to accept the incoming Http request, and return a response with some simple text.
from django.http import HttpResponse def home(request): return HttpResponse('<h1>The Home Page!</h1>') def about(request): return HttpResponse('<h1>About!</h1>')
Now we must configure urls.py once again. Notice how on the third line we are importing that views file. This is what allows us to reference the functions from views.py inside of urls.py. Line 6 is a simple expression that means when you go to the domain with no additional URL parameters, then fire the home() function inside of views.py.
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.home), path('admin/', admin.site.urls), path('about/', views.about) ]
Testing this second route shows us that indeed, this URL and View function combo is also working great!
Learn More About Django URLs and Views
- URLs lead the way (mattlayman.com)
- Django url patterns python (geeksforgeeks.org)
- Python django views (medium.com)
- Views and urlconfs in django (overiq.com)
- Django url and views (stackoverflow.com)
- Django documentation for URLs (docs.djangoproject.com)
- Django URLs (tutorial.djangogirls.org)
- Django Generic views (developer.mozilla.org)
Django URLs and Views Summary
URLs are the front door to your web application in Django. You can configure how this Django routing happens in urls.py. The views.py file is where you can define your view functions. These functions are what determine what the application does based on the URL that a user visits in a web browser. This is a similar concept to web application frameworks in any other language as well. Django’s approach is both elegant and easy to use.