How to Create URLs and Routing in Django


Introduction

In Django, creating URLs and routing is fundamental to building web applications. URL patterns map URLs to views, allowing you to control how web requests are handled. In this guide, we'll explore how to create URLs and routing in Django.


Prerequisites

Before you begin, make sure you have the following prerequisites in place:

  • Django: You should have Django installed. If not, use pip install django to install it.
  • Django Project: You should have a Django project set up. If not, refer to the guide on creating your first Django project.
  • Views: Ensure you have view functions or classes defined in your Django app. If not, refer to the guide on handling URL requests in Django.

Creating URL Patterns

To create URL patterns in Django, you'll define regular expressions that map URLs to view functions or classes.


Sample Code

In your Django app's urls.py file, define URL patterns using the path function. For example:

from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('about/', views.about, name='about'),
path('contact/', views.contact, name='contact'),
]

Using URL Patterns

Once you've defined URL patterns, Django's URL dispatcher will match incoming URLs to the appropriate view functions or classes based on the defined patterns.


Sample Code

In your view functions in views.py, you can handle requests associated with specific URL patterns. For example:

from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to the home page")
def about(request):
return HttpResponse("Learn more about us")
def contact(request):
return HttpResponse("Contact us here")

Conclusion

Creating URL patterns and routing in Django is a key part of building web applications. By defining URL patterns and associating them with views, you can control how web requests are handled, creating a logical structure for your application.