Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn Django URLs


What Are Django URLs?

In Django, a URL (Uniform Resource Locator) represents a specific web address where users can access content or perform actions. The URL routing system allows you to define which views are associated with specific URLs. This helps Django understand which view to call when a user visits a particular address on your website.


Basic URL Configuration

Django uses a urls.py file to define URL patterns for a project or an app. This file typically contains a list of URL patterns, each mapping a specific path to a corresponding view. Here's a simple example:

from django.urls import path
from . import views # Import your views

urlpatterns = [
path('hello/', views.hello_world), # Maps the URL /hello/ to the hello_world view
path('home/', views.home), # Maps the URL /home/ to the home view
]

In this example:


URL Parameters

Django URLs can include dynamic components, allowing you to capture variables from the URL. This is useful for creating URLs that contain IDs, names, or other unique identifiers. Here's an example that captures a user ID from the URL:

urlpatterns = [
path('user 'int:user_id', views.user_profile), # Captures an integer user_id from the URL
]

In this example:

In the view, you can retrieve the captured parameter and use it to perform tasks:


def user_profile(request, user_id):
return HttpResponse(f"User ID: {user_id}")

In this example:



Including URLs from Different Apps

In a Django project with multiple apps, it's common to have separate urls.py files for each app and include them in the project's main URL configuration. This approach helps organize URLs by app. Here's an example of including an app's URLs in the main project urls.py:

from django.urls import include, path
from django.contrib import admin # Admin interface URL

urlpatterns = [
path('admin/', admin.site.urls), # URL for the admin interface
path('myapp/', include('myapp.urls')), # Include URLs from 'myapp'
]


Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java