A website can have many pages and each page has its own unique Route. What do we man by Route? A Route can be thought of as the full URL that displays in the Web Browser URL field. For example, when you want to visit Apple on the internet, you would type https://www.apple.com/ into the Web Browser. This is a specific URL or Route. If you wanted to learn about the iPhone however, you would use a different route such as https://www.apple.com/iphone/. Django has an excellent URL Dispatcher that lets you set up your website routing however you like. As we begin to build out our application, we’ll see this in action.
urls.py In App Folder
Creating a Django App automatically generates several Python files for you. One file it does not create is the urls.py file. This is because you could use the urls.py file at the root level of the project, but it is also perfectly valid for each individual App to have its own urls.py file. In our case, we can create a new urls.py file for this App now.
Creating A Route
To create a route in Django, we are going to use the path() function. In our goals App let’s imagine we are going to have daily, weekly, and monthly goals. We need to think about what routes a user will visit in a Web Browser to see goals. Our first route will deal with daily goals.
C:\python\djangoprojects\myproject\goals\urls.py
from django.urls import path
from . import views
urlpatterns = [
path('daily', views.index)
]
With the development running, we can now try to visit http://127.0.0.1:8000/goals/daily but we get an error:
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/goals/daily Using the URLconf defined in myproject.urls, Django tried these URL patterns, in this order: admin/ The current path, goals/daily, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
Using include()
Configuring a route in the urls.py of a Django App is not enough for it to work. We now have to include the Apps routing in the main projects urls.py. This is how we can do that.
C:\python\djangoprojects\myproject\myproject\urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('goals/', include('goals.urls'))
]
Note that in order to use the include() function, we first import it from django.urls. Once that is complete, we use the highlighted line to configure any routes that go to http://127.0.0.1:8000/goals will actually use the URLconf found in the urls.py of the goals App.
Routing To Views
Finally, we need to add view functions to respond to incoming HTTP requests from the router. If we look at the goals App urls.py we see path(‘daily’, views.index) contained in the source code. What this means is that when a GET request is made to http://127.0.0.1:8000/goals/daily, then the index() function of views.py should run. We don’t have that function defined yet so let’s do that now.
C:\python\djangoprojects\myproject\goals\views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse('Hello Django')
First, we import HttpResponse from django.http, then we set up a return statement that simply returns an HttpResponse with the text of ‘Hello Django’. When we visit http://127.0.0.1:8000/goals/daily in the Web Browser, it looks like it is working!
Creating More Custom Routes
The goals app is going to offer daily, weekly, and monthly goals. Let’s rewrite our urls.py and view.py files to reflect that thought process. So we want to have three different routes such as:
Each of these is a unique entry point into the application, and each should correspond to a unique view function to run when the particular URL is visited in a web browser. First, we can modify the goals/urls.py file like so.
C:\python\djangoprojects\myproject\goals\urls.py
from django.urls import path
from . import views
urlpatterns = [
path('daily', views.daily),
path('weekly', views.weekly),
path('monthly', views.monthly),
]
Note that we have already configured the project level urls.py with the include function for the goals app. That means we don’t have to worry about editing two urls.py files any longer. As long as we are working on this particular goals app, we now only have to adjust the urls.py in this app.
Now in the view.py file, we want to have three functions. These will be the daily(), weekly() and monthly() functions. Each will just return some text in an HTTP Response, but it is a good example of how routing in Django works for now.
C:\python\djangoprojects\myproject\goals\views.py
from django.shortcuts import render
from django.http import HttpResponse
def daily(request):
return HttpResponse('Daily Goals')
def weekly(request):
return HttpResponse('Weekly Goals')
def monthly(request):
return HttpResponse('Monthly Goals')
Each of these routes is now working nicely.
Learn More About Django Routing
- Django Topics Http Urls (docs.djangoproject.com)
- Django Api Guide Routers (django-rest-framework.org)
- Django Urls (tutorial.djangogirls.org)
- Django Url Mapping (tutorialspoint.com)
- Django Urls Path Examples (fullstackpython.com)
- Python Django Urls In Django (ketaniralepatil.com)
- Django Example Adding A Database Routing File (riptutorial.com)
- Django Simple Channels Example (devarea.com)
- How Url Routing In Django Works (henrydangprg.com)