Add URL Patterns
In the previous section, we prepared two views using a function-based view and a class-based view; however, those views are not linked with URLs yet. In this section, we'll add URL patterns for the views.
Add 'include' in the urls.py file
At this stage, there is only one urls.py created by the django-admin startproject
command. The best practice to write URL patterns that are specific to the app is by creating a new urls.py file under the app directory. This is because you may add other apps to the project later. (We'll explain the app structure in the next section.)
The code below is an example of editing the main urls.py file. The yellow parts of the code are added in this example.
The key points here are:
- import the
include
module - add new
urlpatterns
to include URLs written in the test_app
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('test-app/', include('test_app.urls')),
]
Create a new urls.py file under the app directory
By the changes above, the path in the main urls.py is directed to the urls.py file in the app directory, which we haven't created yet.
To create the file, change the current working directory to the app directory. And create a new urls.py file.
cd ../test_app
touch urls.py
Or, you can create the directory and file from the left sidebar of VS Code.
The code below is an example of how to edit the urls.py file under the app directory.
The key points here are:
- Import the
path
function that is used for defining URL patterns - Import the following views created in the previous section. Use a path '
.views
' to define the location of the viewsfunction_view_test
ClassViewTest
- Add two URL patterns
- '
test-function/
' to callfunction_view_test
- '
test-class/
' to callClassViewTest
(you need to add.as_view()
when you call a class-based view)
- '
from django.urls import path
from .views import function_view_test, ClassViewTest
urlpatterns = [
path('test-function/', function_view_test),
path('test-class/', ClassViewTest.as_view()),
]
Check the URLs
To check if the views are working, execute the runserver
command. Make sure your are running the command from the project directory.
python manage.py runserver
When the server is running, go to the following URLs. You'll see the results in the images below.
Function-based View
Class-based View