In Django, handling web page navigation is done through the URL dispatcher, which connects URLs to views using urls.py files. Each Django project includes a project-level urls.py (e.g. project_name/urls.py) and optinal app-level urls.py files in each app (like app_name/urls.py) to keep things organized.
URLs
URLs in Django
Project Level
The project level urls.py file (project_name/urls.py) acts as the main router for your entire Django site. It doesn't handle individual pages directly but instead includes each app's URL configuration.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
# Include the URLs defined in the app_name urls.py file
path('app_name/', include('app_name.urls')),
]
The line
path('HTML/', include(app_name.urls'))
tells Django that "For any URL that starts with /app_name/, check app_name/urls.py for further routing." This
allows you to keep your build modular by letting each app manage its own URL patterns.
It is important that the first parameter is given an name ending with a forward slash. This will appear in the URL and giving it a '/' allows subsequent child pages to be amended easily.
The admin path is the default /admin route for the admin login.
App Level
In each app, you can create a urls.py file to define the specific pages (views) for that app.
# app_name/urls.py
from django.urls import path
from . import views # Import views from the same app
urlpatterns = [
path('', views.view_function_1, name="app_name_function_1"),
path('example_url/', views.view_function_2, name="app_name_function_2"),
]
The first path has an empty '' referring to the base URL for this app. This is defined in the project level urls.py file; in our example it is 'app_name/'. The second path has a further defined path of 'example_url/'. This will take the base URL 'app_name/' and append 'example_url/' to it. This results in the two URLs:
- https://www.website_name.com/app_name/
- https://www.website_name.com/app_name/example_url/
The second parameters given refer to the views. We import the app views at the top and access each defined function with dot notation. For example a function in our app's views.py may be called 'view_function_1' and would render the homepage. 'view_function_2' may render a contact page.
Finally the third parameter is used to assign a name/variable to the URL. This is used mainly in the templating
language to define internal hyperlinks. For example if you had
name='django_home'
in an anchor tag directing to this URL, you would put
href="/Django/home/".