In Django, URLs are used to define the paths through which users can access different parts of your web application. The URLconf (URL configuration) maps specific URL patterns to corresponding views, which handle the request and return a response.
How Django URL Mapping Works?
1. User Request: A user visits a URL like http://abc.com/home.
2. URLconf: Django matches the URL against patterns defined in urls.py.
3. View: The matched pattern invokes the corresponding view.
4. Response: The view processes the request and returns a response (HTML, JSON, etc.).
URL Syntax:
Django uses the path() function to define URL patterns.
path(route, view, kwargs=None, name=None)
route: The URL pattern to match (e.g., ‘about/’).
view: The view function/class to handle the request.
kwargs: Optional parameters passed to the view.
name: A unique name to refer to the URL (useful in templates and redirects).
How to create Django URLs?
There are two types of creation of Django URLs.
1. Project-Level URLs
When you create a Django project, a urls.py file is generated in the project folder (e.g., myproject/urls.py). This file routes top-level URLs and includes app-specific URLs.
Example (myproject/urls.py):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls), # Admin site
path('myapp/', include('myapp.urls')), # Include URLs from an app
]
2. App-Level URLs
Each app can have its own urls.py to defining app-specific routes.
Example (myapp/urls.py):
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'), # Root URL of the app
path('about/', views.about, name='about'),
]
How to create Dynamic URLs?
Django URLs can capture dynamic values using <type:variable> syntax.<int:variable>: Matches an integer (e.g., /article/2/).
<str:variable>: Matches a string (default).
Example:
from django.urls import path
from . import views
urlpatterns = [
path('article/<int:id>/', views.article, name='article'), # Example: /article/2/
path('user/<str:username>/', views.user_profile, name='user_profile'), # Example: /user/john/
]
C# Dictionary – Interview Questions
Q 1: What is urls.py?
Ans: It maps URLs to views.
Q 2: What is URL routing?
Ans: Matching URL patterns to views.
Q 3: What is include() used for?
Ans: To include app-specific URLs.
Q 4: What is path() function?
Ans: Defines URL patterns.
Q 5: Can Django handle dynamic URLs?
Ans: Yes, using path converters.
Django URLs – Objective Questions (MCQs)
Q1. Which file in a Django project stores the main URL configuration?
Q2. Which function is used to define URL patterns?
Q3. To include an app’s URL file inside the project URL file, which function is used?
Q4. The URL dispatcher in Django maps URLs to:
Q5. The dynamic parameter in a URL pattern is written using: