1.B] Discuss the process of mapping URLs to views in Django with an example.
Answer:
Mapping URLs to Views in Django
URL mapping is done using a URL configuration file, commonly referred to as a URLconf.
URLconf
A URLconf in Django is a mapping between URL patterns and view functions. It serves as a table of contents for your website, specifying which view function should handle requests for a given URL.
URL Configuration File (urls.py)
When you create a Django project, a default URL configuration file, urls.py
is generated. This file typically includes the following:
from django.conf.urls.defaults import * # Default URL patterns are commented out urlpatterns = patterns('', # Example URL patterns can be included here )
Adding URL Patterns
To map URLs to views, you need to add URL patterns to the urlpatterns
list. Each URL pattern is a tuple where:
- The first element is a regular expression (regex) that matches the requested URL.
- The second element is the view function to call when the URL pattern matches.
Example of URL Mapping
Let’s walk through an example where we want to map the URL /time/
to a view function called current_datetime
.
Step 1: Define the View Function
First, you need a view function that handles the request and returns a response. Define this in your views.py
file:
# mysite/views.py from django.http import HttpResponse from django.utils import timezone def current_datetime(request): now = timezone.now() html = f"<html><body>It is now {now}.</body></html>" return HttpResponse(html)
Step 2: Update the URLconf
Edit the urls.py
file to include the URL pattern that maps to the current_datetime
view function:
# mysite/urls.py from django.conf.urls import patterns from mysite.views import current_datetime urlpatterns = patterns('', ('time/', current_datetime), )
In this configuration:
'time/'
is a regular expression pattern that matches the URL/time/
.current_datetime
is the view function that will handle requests to this URL.