How to create a function-based view in Django

In this Python Django tutorial, I will explain how to create a function-based view in Django in simple steps.

The view is a function that takes web requests and returns web responses. So, while working on any Django project we always need a view as it contains the main logic.

So, here we will see:

  • What is a function-based view in Django?
  • How to create a function-based view in Django
  • How to create a model in Django
  • How to create a form from a model in Django
  • How to create a function-based view in Django to create a record

At the end of this article, you can also download the code for the function-based view in Django.

Create a Function-based view in Django

Now, let us first understand what is Django function-based view and learn step by step to create Django function-based view to create a record.

Django Function-Based View

A view is where the application’s logic is written.

A function-based view is basically a python function that accepts web requests and returns web responses. The response could be anything, including an XML file, an image, an error, a redirect, or HTML text.

We will generally call these functions as view function, or view, or view function of the application.

Django Function-Based View Advantages

Beginners can readily comprehend function-based views because they are user-friendly for them.

  • It is simple to use and understand.
  • The explicit code flow is provided.
  • Simple use of decorators is provided.
  • Perfect for the specialized function.

Django Function-Based View Disadvantages

The length of the code is the biggest disadvantage of the function-based view.

  • The repetition of code and hard to extend.
  • The HTTP methods will be handled by conditional branching.

Django Function-Based View Syntax

Each function-based view in Django accepts an HttpRequest object as its first argument. Additionally, the function-based view is written in the file of the application as it contains the business logic of an application.

Later, it was necessary to specify a URL name for the function-based view in the file of the project/app.

Below is the syntax to create a function-based view.

def function_name (request):
      return HttpResponse('html/variable/text')

Here the request is an HttpRequest object and HTML/text is an HttpResponse object.

Read: Python Django vs Pyramid

How to create a function-based view in Django to create a record

Now, we will see an example related to the creation of a function-based view in Django which is used to perform create operation.

Set up Django Project

In Django, there is always one project with a variety of apps inside of it. Therefore, we need to establish a project and an app for our project first. Here FunctionBasedViewProject is the name of the project.

django-admin startproject FunctionBasedViewProject

Within the Django project, create a Django app named MyApp using the command as follows.

python startapp MyApp
how to create function based view in django
Django Project and App

Open the file located in the project directory, and add MyApp to the INSTALLED_APP list.

create function based view in django
Install App

In Django, a request first goes to in the project directory, then it is forwarded to the appropriate URLs in in the app directory.

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

urlpatterns = [

Read: Python Django vs ReactJS

Create Django Model

Data for the project is stored in Django models, which are basically tables in our database. Additionally, open the file located in the app directory and add the following code to build models in Django.

from django.db import models

class Employee(models.Model):
    empid = models.IntegerField()
    name = models.CharField(max_length=200)
    gender = models.CharField(max_length=10)
    city = models.CharField(max_length=100)
    def __str__(self):

Here, we create a model named Employee using the Django Model class and it has the following fields.

  • The empid is Django IntegerField.
  • The name, gender, and city are Django CharFields. And there are 200, 10, and 100 character limits for these character fields respectively.
  • And to change the display name of the object in the Django model use the def __str__(self). It will render the item name as the name as we return the

To view the model in the admin application, register it on the admin site. For this, open the file and add the below-given code.

from django.contrib import admin
from .models import Employee

Read: Python Django filter

Django form from the model

To create a form from the model, add the following code to the file we created inside the app directory.

from django import forms
from .models import Employee

class EmployeeForm(forms.ModelForm):
    class Meta:
        model = Employee
        fields = '__all__'

Here, we create a form using forms.ModelForm class named EmployeeForm. And it has all the fields of the Employee model.

Render the Django ModelForm

Create a subdirectory called Templates in the main project directory to store all of the project templates since the front end of a Django application is specified in Templates.

To refer to the Templates directory location, open the file and update the DIRS.

function based view in python django
Location of Template Folder

Create an HTML file named form.html inside the Templates to add the HTML code to it. This HTML code act as a web response object.

<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee Registration</title>
        table {
            border: 8px outset;
            border-radius: 10px;
            border-spacing: 10px;
            padding: 20px;
            margin-left: auto;
            margin-right: auto;

    <h1 align="center">Employee Registration</h1>
    <h3 align="center">Please fill the details to register yourself with our company.</h3>
    <form method="post">
        {% csrf_token %}
        <div style="text-align:center">
            <input type="submit" />

  • The table’s style is first defined in the head tag.
  • The HTML tags h1 and h4 are then used to add the heading for the form inside the body tag.
  • It will render the form by calling the form tag using the POST method.
  • To protect the form from hacker assaults and make it possible to send the data securely, include the csrf_token in the form element.
  • After that, render the form as a table by using the form.as_table tag.
  • Add a submit button as the last step.

Read: Python Django group by

Django Function-Based View for create operation

To create the function-based view which performs create operation on the employee model. Open the file and add the code given below.

from django.shortcuts import render,HttpResponse
from .forms import EmployeeForm

# Create your views here.

def empregistration(request):
    if request.method == 'POST':
        form = EmployeeForm(request.POST)
        if form.is_valid():
            return HttpResponse('Employee is successfully register.')
        form = EmployeeForm()
        context = {
    return render(request, 'form.html', context)
  • Create a view called empregistration and import the EmployeeForm from the file first.
  • After that, execute the if statement to determine whether the request method is POST.
    • If so, just include a request.POST the form method.
    • Call the is_valid method to verify the user’s input. If validation is successful, call the save() method to save the user’s data and return the HttpResponse.
  • The render() function displays a blank registration application form to the user if the request method is GET.

Now, we must map the view with the URL in order to call it, thus we must create a file called in the app directory. Include the code below in it.

from django.urls import path
from . import views

urlpatterns = [
path('', views.empregistration, name='employeeregistration'),

Read: Python filter not in Django

Execute Django Application

To make a migration file that includes code for a model’s tabular schema type the below command in the terminal.

python makemigrations

To builds tables in accordance with the migration file’s schema execute the below command.

python migrate

To launch a development server type the below-given command in the terminal.

python runserver
python django function based view
Execute Django Project

It successfully opens the Django employee registration form that we create using the ModelForm and function-based view which looks like this.

python django function-based view to perform create operation
Employee Registration using Django

Now, fill out the form and click the submit button as shown below.

create a function-based view to create a record in Django
Submit Employee Registration Form in Django

On successful submission of the form, we’ll get the HttpResponse as shown below.

create a function-based view to create a record in python Django
Successfully Submitting the Employee Registration Form in Django

This is how we create a function-based view to perform a create operation in Django.

Download the Django Function-Based View complete code

Here is the code:


With this, we have successfully created a function-based view in Django. We have also learned how to create a function-based view in Django, its advantages and disadvantages, and its syntax.

Additionally, we have covered the following topic.

  • What is a function-based view in Django?
  • How to create a function-based view in Django
  • How to create a model in Django
  • How to create a form from a model in Django
  • How to create a function-based view in Django to create a record

You may also like to read the following Python Django tutorials.