Django URLs in Python Last Updated : 17 May, 2025 Comments Improve Suggest changes Like Article Like Report In Django, views are Python functions that handle HTTP requests. These views process the request and return an HTTP response or an error (e.g., 404 if not found). Each view must be mapped to a specific URL pattern. This mapping is managed through URLConf (URL Configuration).In this article, we'll explore how URL patterns are used in Django, how they are defined in urls.py, and how different URL patterns help in routing requests to appropriate views.Understanding URLConf in DjangoIn Django, the URLConf refers to the process of mapping URLs to views. This mapping is defined in a Python module, usually called urls.py. The configuration module specified in the ROOT_URLCONF setting in settings.py determines which module is used for URL mapping.For a project named myProject, the default ROOT_URLCONF is typically set to 'myProject.urls'. Every URLConf module contains a variable urlpatterns, which is a list or set of URL patterns that Django checks against the requested URL. The patterns are checked in sequence, and when a match is found, the corresponding view is invoked. If no match is found, Django triggers an appropriate error handling view.Structure of URLConf in Django: Python # myProject/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('books.urls')), # Including URL patterns from the books app ] In the above example:path('admin/', admin.site.urls) maps the URL /admin/ to Django's default admin interface.path('', include('books.urls')) tells Django to look for additional URL patterns in the books.urls module, which is typically located in the books app.URL Patterns in DjangoURL patterns are defined inside the urlpatterns list. This list contains the routes Django uses to match incoming URLs to appropriate views.Here is a sample urls.py for the books app: Python # books/urls.py from django.urls import path from . import views urlpatterns = [ path('books//', views.book_detail), # Detail view for a book, identified by primary key (pk) path('books//', views.books_by_genre), # View books by genre path('books/', views.book_index), # List all books ] Explanation:path('books//', views.book_detail): This pattern matches /books/25/, where 25 is an integer representing the primary key (PK) of a book. Django will call views.book_detail(request, pk=25).path('books//', views.books_by_genre): This pattern matches /books/crime/, where crime is a string representing the genre of books. Django will call views.books_by_genre(request, genre="crime").path('books/', views.book_index): This pattern matches /books/, which lists all books. Django will call views.book_index(request).Example: How Django URLs Work — Basic HTML Pages & Navigation1. Define views in views.py: Python from django.http import HttpResponse from django.shortcuts import render def home_view(request): return render(request, 'home.html') def about_view(request): return render(request, 'about.html') def contact_view(request): return render(request, 'contact.html') 2. Create basic templates in your templates/ folder:home.html: HTML <h1>Home Pageh1> <p>Welcome to the home page.p> <a href="/about/">Go to Abouta><br> <a href="/contact/">Go to Contacta> about.html: Python <h1>About Pageh1> <p>This is the about page.p> <a href="/">Go to Homea><br> <a href="/contact/">Go to Contacta> contact.html: HTML <h1>Contact Pageh1> <p>Contact us at [email protected].p> <a href="/">Go to Homea><br> <a href="/about/">Go to Abouta> 3. Define URL patterns in urls.py: Python from django.urls import path from . import views urlpatterns = [ path('', views.home_view, name='home'), path('about/', views.about_view, name='about'), path('contact/', views.contact_view, name='contact'), ] Output:1. Home Page:Home Page2. Click “Go to About”:About Page3. Click “Go to Contact”:Contact PagePath ConvertersIn Django, path converters are used in URL patterns to capture specific values from the URL and pass them to the view as arguments. For example:int – Matches zero or any positive integer.str – Matches any non-empty string, excluding the path separator(‘/’).slug – Matches any slug string, i.e. a string consisting of alphabets, digits, hyphen and under score.path – Matches any non-empty string including the path separator(‘/’)uuid – Matches a UUID(universal unique identifier). Comment More infoAdvertise with us Next Article Get parameters passed by urls in Django A Abhishek De Follow Improve Article Tags : Python Web Technologies Python Django Practice Tags : python Similar Reads Django Tutorial | Learn Django Framework Django is a Python framework that simplifies web development by handling complex tasks for you. It follows the "Don't Repeat Yourself" (DRY) principle, promoting reusable components and making development faster. With built-in features like user authentication, database connections, and CRUD operati 10 min read Django BasicsDjango BasicsDjango is a Python-based web framework which allows us to quickly develop robust web application without much third party installations. It comes with many built-in featuresâlike user authentication, an admin panel and form handlingâthat help you build complex sites without worrying about common web 3 min read Django Installation and SetupInstalling and setting up Django is a straightforward process. Below are the step-by-step instructions to install Django and set up a new Django project on your system.Prerequisites: Before installing Django, make sure you have Python installed on your system. How to Install Django?To Install Django 2 min read When to Use Django? Comparison with other Development StacksPrerequisite - Django Introduction and Installation Django is a high-level Python web framework which allow us to quickly create web applications without all of the installation or dependency problems that we normally face with other frameworks. One should be using Django for web development in the 2 min read Django Project MVT StructureDjango follows the MVT (Model-View-Template) architectural pattern, which is a variation of the traditional MVC (Model-View-Controller) design pattern used in web development. This pattern separates the application into three main components:1. ModelModel acts as the data layer of your application. 2 min read How to Create a Basic Project using MVT in Django ?Prerequisite - Django Project MVT Structure Assuming you have gone through the previous article. This article focuses on creating a basic project to render a template using MVT architecture. We will use MVT (Models, Views, Templates) to render data to a local server. Create a basic Project: To in 2 min read How to Create an App in Django ?In Django, an app is a web application that performs a specific functionality, such as blog posts, user authentication or comments. A single Django project can consist of multiple apps, each designed to handle a particular task. Each app is a modular and reusable component that includes everything n 3 min read Django settings file - step by step ExplanationOnce we create the Django project, it comes with a predefined Directory structure having the following files with each file having its own uses. Let's take an example // Create a Django Project "mysite" django-admin startproject mysite cd /pathTo/mysite // Create a Django app "polls" inside project 3 min read Django viewViews In Django | PythonDjango Views are one of the vital participants of the MVT Structure of Django. As per Django Documentation, A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, a redirect, a 404 error, an XML document, an ima 6 min read Django Function Based ViewsDjango is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks. Django is based on MVT (Model View Template) architecture and revolves around CRUD (Create, Retrieve, Up 7 min read Django Class Based ViewsClass-Based Views (CBVs) allow developers to handle HTTP requests in a structured and reusable way. With CBVs, different HTTP methods (like GET, POST) are handled as separate methods in a class, which helps with code organization and reusability.Advantages of CBVsSeparation of Logic: CBVs separate d 6 min read Class Based vs Function Based Views - Which One is Better to Use in Django?Django, a powerful Python web framework, has become one of the most popular choices for web development due to its simplicity, scalability and versatility. One of the key features of Django is its ability to handle views and these views can be implemented using either Class-Based Views (CBVs) or Fun 6 min read Django Templates Templates are the third and most important part of Django's MVT Structure. A Django template is basically an HTML file that can also include CSS and JavaScript. The Django framework uses these templates to dynamically generate web pages that users interact with. Since Django primarily handles the ba 7 min read Django Static File Static Files such as Images, CSS, or JS files are often loaded via a different app in production websites to avoid loading multiple stuff from the same server. This article revolves around, how you can set up the static app in Django and server Static Files from the same.Create and Activate the Virt 3 min read Django ModelDjango ModelsA Django model is a Python class that represents a database table. Models make it easy to define and work with database tables using simple Python code. Instead of writing complex SQL queries, we use Djangoâs built-in ORM (Object Relational Mapper), which allows us to interact with the database in a 8 min read Django model data types and fields listDjango models represent the structure of your database tables, and fields are the core components of those models. Fields define the type of data each database column can hold and how it should behave. This article covers all major Django model field types and their usage.Defining Fields in a ModelE 4 min read Field Validations and Built-In Fields - Django ModelsField validations in Django help make sure the data you enter into your database is correct and follows certain rules. Django automatically checks the data based on the type of field you use, so you donât have to write extra code to validate it yourself.Django provides built-in validations for every 3 min read How to use User model in Django?The Djangoâs built-in authentication system is great. For the most part we can use it out-of-the-box, saving a lot of development and testing effort. It fits most of the use cases and is very safe. But sometimes we need to do some fine adjustment so to fit our Web application. Commonly we want to st 3 min read Meta Class in Models - DjangoDjango is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. Itâs free and open source. D 3 min read get_object_or_404 method in Django ModelsSome functions are hard as well as boring to code each and every time. But Django users don't have to worry about that because Django has some awesome built-in functions to make our work easy and enjoyable. Let's discuss get_object_or_404() here. What is get_object_or_404 in Django?get_object_or_404 2 min read Django FormsDjango FormsDjango Forms are used to gather input from users, validate that input, and process it, often saving the data to the database. For example, when registering a user, a form collects information like name, email, and password.Django automatically maps form fields to corresponding HTML input elements. I 5 min read How to Create a form using Django FormsThis article explains how to create a basic form using various form fields and attributes. Creating a form in Django is very similar to creating a model, you define the fields you want and specify their types. For example, a registration form might need fields like First Name (CharField), Roll Numbe 2 min read Django Form | Data Types and FieldsWhen collecting user input in Django, forms play a crucial role in validating and processing the data before saving it to the database. Django provides a rich set of built-in form field types that correspond to different kinds of input, making it easy to build complex forms quickly.Each form field t 4 min read Django Form | Build in Fields ArgumentWe utilize Django Forms to collect user data to put in a database. For various purposes, Django provides a range of model field forms with various field patterns. The most important characteristic of Django forms is their ability to handle the foundations of form construction in only a few lines of 3 min read Python | Form validation using djangoPrerequisites: Django Installation | Introduction to DjangoDjango works on an MVT pattern. So there is a need to create data models (or tables). For every table, a model class is created. Suppose there is a form that takes Username, gender, and text as input from the user, the task is to validate th 5 min read Render Django Form Fields ManuallyDjango form fields have several built-in methods to ease the work of the developer but sometimes one needs to implement things manually for customizing User Interface(UI). We have already covered on How to create and use a form in Django?. A form comes with 3 in-built methods that can be used to ren 5 min read Django URLSDjango URLs in PythonIn Django, views are Python functions that handle HTTP requests. These views process the request and return an HTTP response or an error (e.g., 404 if not found). Each view must be mapped to a specific URL pattern. This mapping is managed through URLConf (URL Configuration).In this article, we'll ex 3 min read Get parameters passed by urls in DjangoDjango is a fully fleshed framework which can help you create web applications of any form. This article discusses how to get parameters passed by URLs in django views in order to handle the function for the same. You might have seen various blogs serving with urls like: - www.example.com/articles/ 2 min read url - Django Template TagA Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some 3 min read URLField - Django ModelsURLField is a CharField, for a URL. It is generally used for storing webpage links or particularly called as URLs. It is validated by URLValidator. To store larger text TextField is used. The default form widget for this field is TextInput. Syntax field_name = models.URLField(max_length=200, **optio 4 min read URL fields in serializers - Django REST FrameworkIn Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_n 5 min read Django Admin Interface - Python Prerequisites: Django Introduction and Installation Creating a ProjectThe Django Admin Interface is one of the most powerful features of the Django framework. It provides a ready-to-use interface for managing project data through models, allowing developers and site administrators to perform Create, 3 min read More topics on DjangoHandling Ajax request in DjangoAJAX (Asynchronous JavaScript and XML) is a web development technique that allows a web page to communicate with the server without reloading the entire page. In Django, AJAX is commonly used to enhance user experience by sending and receiving data in the background using JavaScript (or libraries li 3 min read User Groups with Custom Permissions in Django - PythonOur task is to design the backend efficiently following the DRY (Don't Repeat Yourself) principle, by grouping users and assigning permissions accordingly. Users inherit the permissions of their groups.Let's consider a trip booking service, how they work with different plans and packages. There is a 4 min read Django Admin Interface - PythonPrerequisites: Django Introduction and Installation Creating a ProjectThe Django Admin Interface is one of the most powerful features of the Django framework. It provides a ready-to-use interface for managing project data through models, allowing developers and site administrators to perform Create, 3 min read Extending and customizing django-allauth in PythonDjango-allauth is a powerful Django package that simplifies user authentication, registration, account management, and integration with social platforms like Google, Facebook, etc. It builds on Djangoâs built-in authentication system, providing a full suite of ready-to-use views and forms.Prerequisi 4 min read Django - Dealing with Unapplied Migration WarningsDjango is a powerful web framework that provides a clean, reusable architecture to build robust applications quickly. It embraces the DRY (Don't Repeat Yourself) principle, allowing developers to write minimal, efficient code.Create and setup a Django project:Prerequisite: Django - Creating projectA 2 min read Sessions framework using django - PythonDjango sessions let us store data for each user across different pages, even if theyâre not logged in. The data is saved on the server and a small cookie (sessionid) is used to keep track of the user.A session stores information about a site visitor for the duration of their visit (and optionally be 3 min read Django Sign Up and login with confirmation Email | PythonDjango provides a built-in authentication system that handles users, login, logout, and registration. In this article, we will implement a user registration and login system with email confirmation using Django and django-crispy-forms for elegant form rendering.Install crispy forms using the termina 7 min read Like