Create a Function-Based View in Django

Views are essential because they control what your users see and how your application responds to requests. Over the years, I’ve found that function-based views (FBVs) in Django are a great way to lay a solid foundation before moving to more complex concepts like class-based views.

In this article, I’ll walk you through how to create a function-based view in Django. I’ll share my firsthand experience and provide practical examples that are easy to follow.

Let’s begin!

What is a Function-Based View in Django?

Simply put, a function-based view is a Python function that takes a web request and returns a web response. It’s the easy way to handle requests in Django. When I first started working with Django, I appreciated FBVs for their simplicity and clarity. They allow you to write procedural code that’s easy to understand and debug.

Unlike class-based views, which use object-oriented programming principles, FBVs rely on plain Python functions. This makes them ideal for beginners or when you want full control over the request-response cycle.

Check out Compare Two Integers in Python Django

How to Create Your First Function-Based View

Let’s jump into the practical part. I’ll show you how to create a simple FBV that returns a list of US states on a webpage. This example is relevant if you’re building a directory or information site tailored for US users.

Step 1: Set Up Your Django Project and App

If you haven’t already created a Django project, start with the following commands in your terminal:

django-admin startproject usa_info
cd usa_info
python manage.py startapp states

This creates a project called usa_info and an app called states.

Read Build a Chat App in Django

Step 2: Define Your View Function

Open the states/views.py file and add the following code:

from django.http import HttpResponse
from django.shortcuts import render

def states_list(request):
    us_states = [
        'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado',
        'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho',
        'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
        'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
        'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada',
        'New Hampshire', 'New Jersey', 'New Mexico', 'New York',
        'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon',
        'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota',
        'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington',
        'West Virginia', 'Wisconsin', 'Wyoming'
    ]
    return render(request, 'states/states_list.html', {'states': us_states})

Here, the states_list function takes a request object, creates a list of US states, and passes it to a template for rendering.

Step 3: Create the Template

Create a folder named templates inside your states app directory. Then, inside the templates folder, create another folder named states. Inside states/templates/states/, create a file called states_list.html and add this code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>List of US States</title>
</head>
<body>
    <h1>US States</h1>
    <ul>
        {% for state in states %}
            <li>{{ state }}</li>
        {% endfor %}
    </ul>
</body>
</html>

This template simply loops over the states list and displays each state as a list item.

Check out How to Deploy an AI Model with Django

Step 4: Configure URL Patterns

Next, you need to map a URL to your view. Open states/urls.py (create this file if it doesn’t exist) and add:

from django.urls import path
from .views import states_list

urlpatterns = [
    path('states/', states_list, name='states_list'),
]

Then, include this URL configuration in your project’s main urls.py (usa_info/urls.py):

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

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

Step 5: Run the Server and Test

Finally, run the Django development server:

python manage.py runserver

Open your browser and go to http://127.0.0.1:8000/states/. You should see a neat list of US states displayed.

I executed the above example code and added the screenshot below.

django function based views

Read File Upload in Django

Alternative: Return JSON Response in Function-Based Views

Sometimes, especially when building APIs or dynamic web apps, you might want to return JSON data instead of rendering HTML.

Here’s how you can modify the above view to return JSON:

from django.http import JsonResponse

def states_list_json(request):
    us_states = [
        'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado',
        'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho',
        'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
        'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
        'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada',
        'New Hampshire', 'New Jersey', 'New Mexico', 'New York',
        'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon',
        'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota',
        'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington',
        'West Virginia', 'Wisconsin', 'Wyoming'
    ]
    return JsonResponse({'states': us_states})

Update your urls.py to include this new route:

path('states/json/', states_list_json, name='states_list_json'),

When you visit http://127.0.0.1:8000/states/json/, you’ll get a JSON response with the list of states. This is especially useful for frontend frameworks or mobile apps consuming your Django backend.

Check out JWT Authentication Using Django Rest Framework

Handle HTTP Methods in Function-Based Views

In real-world applications, you often need to handle different HTTP methods like GET, POST, PUT, or DELETE within the same view. With function-based views, this is straightforward.

Here’s an example of a simple contact form handler that accepts GET and POST requests:

from django.shortcuts import render
from django.http import HttpResponse

def contact(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        message = request.POST.get('message')
        # Here you could save the message or send an email
        return HttpResponse(f"Thanks for your message, {name}!")
    return render(request, 'states/contact.html')

Create a simple form in contact.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Contact Us</title>
</head>
<body>
    <h1>Contact Us</h1>
    <form method="post">
        {% csrf_token %}
        <label for="name">Name:</label><br>
        <input type="text" id="name" name="name" required><br><br>
        <label for="message">Message:</label><br>
        <textarea id="message" name="message" required></textarea><br><br>
        <button type="submit">Send</button>
    </form>
</body>
</html>

Add this to your urls.py:

path('contact/', contact, name='contact'),

This example shows how easy it is to handle form submission using function-based views.

Read Create an API in Python Django

Why Choose Function-Based Views?

From my experience, function-based views are perfect when you want simplicity and direct control over your code. They are easy to write and understand, especially if you’re new to Django or coming from a procedural programming background.

FBVs are also flexible. You can handle different HTTP methods, return HTML or JSON, and manage request data without much boilerplate.

However, for larger projects, class-based views might offer better reusability and structure. But starting with FBVs helps you grasp Django’s core concepts without overwhelming complexity.

I hope this guide has given you a clear understanding of how to create function-based views in Django. With the examples provided, you can now build simple web pages, handle forms, and return JSON data with ease.

If you want to deepen your Django skills, try extending these views, adding models, or exploring Django’s class-based views next. Happy coding!

Other Django articles you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.