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 views.py 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 urls.py 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 manage.py startapp MyApp
Open the settings.py file located in the project directory, and add MyApp to the INSTALLED_APP list.
In Django, a request first goes to urls.py in the project directory, then it is forwarded to the appropriate URLs in urls.py in the app directory.
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('MyApp.urls')),
]
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 models.py 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):
return self.name
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 self.name.
To view the model in the admin application, register it on the admin site. For this, open the admin.py file and add the below-given code.
from django.contrib import admin
from .models import Employee
admin.site.register(Employee)
Read: Python Django filter
Django form from the model
To create a form from the model, add the following code to the forms.py 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 settings.py file and update the DIRS.
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">
<head>
<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>
<style>
table {
border: 8px outset;
border-radius: 10px;
border-spacing: 10px;
padding: 20px;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<h1 align="center">Employee Registration</h1>
<hr>
<h3 align="center">Please fill the details to register yourself with our company.</h3>
<hr>
<br>
<form method="post">
{% csrf_token %}
<table>
{{form.as_table}}
</table>
<br><br>
<div style="text-align:center">
<input type="submit" />
</div>
</form>
</body>
</html>
- 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 views.py 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():
form.save()
return HttpResponse('Employee is successfully register.')
else:
form = EmployeeForm()
context = {
'form':form,
}
return render(request, 'form.html', context)
- Create a view called empregistration and import the EmployeeForm from the forms.py 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 urls.py 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 manage.py makemigrations
To builds tables in accordance with the migration file’s schema execute the below command.
python manage.py migrate
To launch a development server type the below-given command in the terminal.
python manage.py runserver
It successfully opens the Django employee registration form that we create using the ModelForm and function-based view which looks like this.
Now, fill out the form and click the submit button as shown below.
On successful submission of the form, we’ll get the HttpResponse as shown below.
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:
Conclusion
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.
- Get URL parameters in Django
- Django get all data from POST request
- If statement in Django template
- Python Django random number
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.