Paramclasses Academy - Blog

Tutorials Details

Django URL Routing and Views: Complete Guide with Practical Examples

Django URL Routing and Views: Complete Guide with Practical Examples

October 19, 2026

Django URL Routing and Views: Complete Guide with Practical Examples

Introduction to URL Routing and Views

Every website has URLs that allow users to access different pages and features. For example, a student management website might have a home page, a student list page, a registration page, and an admin panel.

Django uses URL routing to determine which part of the application should handle a particular request. Views process those requests and return responses to the browser.

In the previous tutorial, you learned about the Django project structure and important files. In this tutorial, you will learn how urls.py and views.py work together to display web pages.

What Is URL Routing in Django?

URL routing is the process of connecting a URL pattern to a particular view or another URL configuration.

For example:

  • / — Home page

  • /about/ — About page

  • /students/ — Student list

  • /contact/ — Contact page

When a user visits a URL, Django checks the configured URL patterns in order and calls the view associated with the first matching pattern.

If no pattern matches, Django normally returns a 404 Not Found response.

What Is a View in Django?

A view is a Python function or class that receives a web request and returns a response.

A view can:

  • Return plain text or HTML.

  • Retrieve data from a database.

  • Process submitted form data.

  • Render an HTML template.

  • Redirect a user to another URL.

  • Return JSON data for an API.

Django supports both function-based views and class-based views.

Step 1: Create a Django Project

If you completed Module 2, you can use your existing project.

Otherwise, create a project by running:

django-admin startproject myproject
cd myproject
python manage.py runserver

Open the local development URL shown in your terminal, commonly:

http://127.0.0.1:8000/

Keep the development server running while testing your changes.

Step 2: Understand urls.py

The project's urls.py file contains URL patterns that connect requested paths to views.

A new Django project normally contains code similar to this:

from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
]

Explanation

from django.urls import path: Imports the function used to define URL patterns.

urlpatterns: A list of URL patterns Django checks when processing incoming requests.

path('admin/', admin.site.urls): Connects the /admin/ URL to Django's administration interface.

You can add additional URL patterns to display your own pages.

Step 3: Create Your First View

Open the views.py file inside your Django app.

If you followed Module 3, you may already have an app named students. Otherwise, create one:

python manage.py startapp students

Add 'students' to INSTALLED_APPS in your project's settings.py.

Now open students/views.py and write:

from django.http import HttpResponse

def home(request):
    return HttpResponse("Welcome to My Django Website!")

Explanation

HttpResponse: Returns an HTTP response to the browser.

home(request): Defines a function-based view named home.

request: Contains information about the incoming HTTP request.

return: Sends the response generated by the view back to Django.

This is a simple function-based view because it uses a Python function to process the request.

Step 4: Connect the View to a URL

Open your project's main urls.py file and update it:

from django.contrib import admin
from django.urls import path
from students import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name='home'),
]

How Does This Work?

The expression:

path('', views.home, name='home')

connects the root URL / to the home view.

The empty path '' represents the root of the current URL configuration.

The name 'home' gives this URL pattern a reusable name.

Now open:

http://127.0.0.1:8000/

You should see:

Welcome to My Django Website!

Your first custom Django view is now connected to a URL.

Step 5: Create Multiple URL Patterns

A real website needs more than one page.

Update students/views.py:

from django.http import HttpResponse

def home(request):
    return HttpResponse("Welcome to My Django Website!")

def about(request):
    return HttpResponse("This is the About page.")

def contact(request):
    return HttpResponse("Contact us for more information.")

Now update the project's urls.py:

from django.contrib import admin
from django.urls import path
from students import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name='home'),
    path('about/', views.about, name='about'),
    path('contact/', views.contact, name='contact'),
]

Test these URLs in your browser:

  • http://127.0.0.1:8000/

  • http://127.0.0.1:8000/about/

  • http://127.0.0.1:8000/contact/

Each URL should display its corresponding message.

Step 6: Understand the path() Function

Django's path() function is used to define URL patterns.

Its general structure is:

path(route, view, kwargs=None, name=None)

Parameters

route: The URL pattern to match.

view: The view function, class-based view, or included URL configuration that handles the matching request.

kwargs: Optional additional keyword arguments passed to the view.

name: An optional name used to refer to the URL elsewhere in the application.

Example:

path('about/', views.about, name='about')

This defines a route for the About page and names it about.

Step 7: Use Dynamic URL Parameters

Sometimes a URL needs to include a value, such as a student ID.

For example:

/students/5/

The number 5 could represent the ID of a student record.

Create a view in students/views.py:

from django.http import HttpResponse

def student_detail(request, student_id):
    return HttpResponse(
        f"Student ID: {student_id}"
    )

Then add the URL pattern to the project's urls.py:

path(
    'students/<int:student_id>/',
    views.student_detail,
    name='student_detail'
)

Now visit:

http://127.0.0.1:8000/students/5/

The response will be:

Student ID: 5

What Does int Mean?

int: Tells Django to match an integer value.

student_id: Names the captured value passed to the view.

Other commonly used path converters include:

  • str — Matches a non-empty string that does not include a slash.

  • int — Matches a positive integer.

  • slug — Matches letters, numbers, hyphens, and underscores.

  • uuid — Matches a UUID value.

  • path — Matches a non-empty string that can include slashes.

Choose the converter that matches the data expected by the route.

Step 8: Understand Function-Based Views

A function-based view is a Python function that accepts a request and returns a response.

Example:

from django.http import HttpResponse

def welcome(request):
    return HttpResponse("Welcome to Django!")

Advantages

  1. Easy for beginners to understand.

  2. Suitable for simple pages and straightforward request handling.

  3. Gives developers direct control over the request-processing logic.

Function-based views are a good starting point when learning Django.

Step 9: Render an HTML Template from a View

Returning plain text is useful for learning, but real websites generally display HTML pages.

Inside your students app, create this folder structure:

students/
└── templates/
    └── students/
        └── home.html

In home.html, write:

<!DOCTYPE html>
<html>
<head>
    <title>Django Home</title>
</head>
<body>
    <h1>Welcome to My Django Website</h1>
    <p>This page is rendered using a Django template.</p>
</body>
</html>

Now update students/views.py:

from django.shortcuts import render

def home(request):
    return render(request, 'students/home.html')

Open the root URL again.

Django will render the HTML template and return the resulting page to the browser.

This example assumes your students app is installed and app template discovery is enabled in the template settings.

Step 10: Pass Dynamic Data to a Template

Views can pass data to templates through a context dictionary.

Update students/views.py:

from django.shortcuts import render

def home(request):
    context = {
        'student_name': 'Rahul',
        'course_name': 'Django Development',
    }

    return render(
        request,
        'students/home.html',
        context
    )

Update students/templates/students/home.html:

<!DOCTYPE html>
<html>
<head>
    <title>Student Dashboard</title>
</head>
<body>
    <h1>Welcome, {{ student_name }}!</h1>
    <p>Course: {{ course_name }}</p>
</body>
</html>

The browser should display:

Welcome, Rahul!

Course: Django Development

The double curly braces {{ }} represent template variables.

In a real application, this data could come from a database instead of being written directly in the view.

Step 11: What Is render()?

Django's render() shortcut combines a template with a context dictionary and returns an HTTP response.

Example:

return render(request, 'students/home.html')

When data needs to be passed to the template:

return render(
    request,
    'students/home.html',
    {'name': 'Rahul'}
)

The first argument is the request, the second is the template name, and the optional third argument contains the context data.

Use render() when you want to return a rendered HTML page.

Step 12: What Is redirect()?

The redirect() shortcut sends the browser to another URL.

For example:

from django.shortcuts import redirect

def go_home(request):
    return redirect('home')

Here, 'home' is the name of a URL pattern.

Django resolves the URL name and redirects the browser to that destination.

Redirects are useful after actions such as successful form submissions or completing a workflow.

Important: The URL name must exist in the project's URL configuration or in an included URL configuration.

Step 13: Introduction to Class-Based Views

Django also supports class-based views, which organize request handling into Python classes.

For example:

from django.http import HttpResponse
from django.views import View

class HomeView(View):
    def get(self, request):
        return HttpResponse(
            "Welcome from a class-based view!"
        )

Connect the class to a URL using as_view():

from django.urls import path
from students.views import HomeView

urlpatterns = [
    path('', HomeView.as_view(), name='home'),
]

Function-Based Views vs Class-Based Views

Function-based views: Use Python functions and are often straightforward for beginners.

Class-based views: Use classes and can provide reusable behavior through inheritance and built-in generic views.

Neither approach is automatically best for every situation. Choose according to the requirements and complexity of the application.

Step 14: Understand HTTP Methods in Views

HTTP methods describe the type of operation a client requests.

Common methods include:

GET: Requests a resource, such as displaying a page.

POST: Submits data, commonly through a form.

PUT: Commonly replaces a resource in APIs.

PATCH: Commonly partially updates a resource in APIs.

DELETE: Requests deletion of a resource.

For a basic Django function-based view, you can check the request method:

from django.http import HttpResponse

def contact(request):
    if request.method == 'POST':
        return HttpResponse("Form submitted.")

    return HttpResponse("Display the contact form.")

This is only a basic illustration. A real form should use Django's form validation and appropriate CSRF protection.

Do not use GET requests to perform operations that change important data.

Step 15: Understand the Complete Request-Response Flow

Suppose a user opens /about/.

The general process is:

  1. The browser sends an HTTP request.

  2. Django receives the request.

  3. Django checks the project's URL patterns.

  4. The matching route identifies the appropriate view.

  5. The view processes the request.

  6. The view returns an HTTP response, potentially using a template or database query.

  7. Django sends the response to the browser.

This process connects URL routing and views to the overall functioning of a Django website.

Common Errors and Their Solutions

Error 1: Page Not Found (404)

Cause: The URL pattern may be missing, or the requested URL may not match it.

Solution: Check urlpatterns, the route spelling, and the URL entered in the browser.

Error 2: View Does Not Exist

Cause: The view name may be misspelled, or the wrong module may have been imported.

Solution: Verify the function name and import statement.

Error 3: Missing Required Argument

Cause: A dynamic URL parameter may not match the view's function parameters.

Solution: Make sure the captured parameter name and view argument are consistent.

Error 4: TemplateDoesNotExist

Cause: The template may be missing or saved in an incorrect directory.

Solution: Verify the template path, app installation, and template configuration.

Error 5: No Module Named students

Cause: The app may not exist or the import path may be incorrect.

Solution: Create the app if needed and verify that your code is importing it from the correct location.

Error 6: Duplicate URL Names

Cause: Multiple URL patterns may use the same name, creating ambiguity when resolving a URL by name.

Solution: Use meaningful, distinct names or namespaces where appropriate.

Frequently Asked Questions (FAQs)

Q1. What is URL routing in Django?

Answer: URL routing maps URL patterns to the views or URL configurations that handle incoming requests.

Q2. What is a Django view?

Answer: A view is a Python function or class that processes a request and returns a response.

Q3. What is the purpose of urls.py?

Answer: It defines the URL patterns used by Django to route incoming requests.

Q4. What is the purpose of views.py?

Answer: It commonly contains application views that process requests and generate responses.

Q5. What is path() in Django?

Answer: path() defines a URL pattern and associates it with a view or another URL configuration.

Q6. What is a dynamic URL?

Answer: A dynamic URL captures values, such as an integer student ID, from the requested path.

Q7. What is the difference between HttpResponse and render()?

Answer: HttpResponse returns an HTTP response directly, while render() renders a template with optional context data and returns an HTTP response.

Q8. What is redirect() used for?

Answer: It redirects the browser to a destination URL.

Q9. What is the difference between function-based and class-based views?

Answer: Function-based views use functions, while class-based views use classes and can organize reusable behavior through inheritance.

Q10. What is a 404 error?

Answer: It indicates that the requested resource or matching route could not be found.

Q11. What does the name parameter do in path()?

Answer: It assigns a reusable name to a URL pattern so that the URL can be resolved elsewhere in the application.

Q12. Can a Django view return JSON?

Answer: Yes. A view can use JsonResponse to return JSON data.

Important Interview Questions and Answers

Q1. Explain Django's URL routing process.

Answer: Django checks the configured URL patterns in order and invokes the view associated with the first matching pattern.

Q2. What is the first argument passed to a function-based view?

Answer: The first argument is the HttpRequest object, commonly named request.

Q3. Why do we use URL names?

Answer: URL names allow developers to refer to routes without hardcoding the complete URL throughout the application.

Q4. What is a URL converter?

Answer: A URL converter specifies the type and format of the value that a URL pattern can capture.

Q5. What does <int:student_id> mean?

Answer: It captures an integer from the URL and passes it to the view using the parameter name student_id.

Q6. What is the purpose of render()?

Answer: It combines a template with context data and returns a rendered HTTP response.

Q7. What is the purpose of redirect()?

Answer: It redirects the browser to another URL.

Q8. What is a class-based view?

Answer: It is a view implemented as a Python class, usually connected to a URL through as_view().

Q9. How can a view distinguish GET and POST requests?

Answer: It can check request.method or use class-based view methods such as get() and post().

Q10. What is the difference between a URL pattern and a view?

Answer: A URL pattern determines which handler should receive a request, while the view processes that request and returns a response.

Practical Exercise

Build a small multi-page Django website by completing these tasks:

  1. Create a Django app named students.

  2. Create a home view that returns a welcome message.

  3. Create About and Contact views.

  4. Connect all three views to URL patterns.

  5. Add a dynamic student detail URL using an integer ID.

  6. Create an HTML template for the home page.

  7. Pass a student's name from the view to the template.

  8. Add a URL name to each route.

  9. Test each page in the browser.

  10. Intentionally enter an incorrect URL and observe the 404 response.

Expected Learning Outcome

After completing this exercise, you should understand how a Django URL connects to a view, how views return responses, and how templates display dynamic information.

Conclusion

Django URL routing and views are fundamental parts of web application development.

URL patterns connect incoming requests to the appropriate handlers, while views process those requests and return responses. With templates, dynamic URL parameters, and URL names, you can build structured and maintainable multi-page websites.

In the next tutorial, you will learn about Django Templates and Template Language, including template variables, tags, filters, and template inheritance.