1 - About Django Model Form
Suppose we have a model containing various fields, we don't need to recode the fields in the html file. Django does this automatically for us to reduce application development time. This is a class used to create an HTML form using the existing model. In addition, the form created will be dynamic, i.e. it allows data to be inserted into the database. It is an effective way to create a form without writing HTML code. For this reason, Django provides the ModelForm helper class which allows us to create a Form class from a Django model.
2 - Creating a form using the ModelForm class
To make it simple, we are going to create a form for a small student management application containing the following fields:
- name
- section
Before proceeding to the creation of a model, you must first create app called for example manageStudents:
python manage.py startapp manageStudents
and register it in to the mysite/settings.py file:
Then save your app in the file: settings.py:
INSTALLED_APPS = [
'manageStudents.apps.ManagestudentsConfig',
xxxxxxxxxxxxxxxxx,
xxxxxxxxxxxxxxxxx,]
Now create the model Students in the file models.py
from django.db import models
class Students(models.Model):
name = models.CharField(max_length=25)
email = models.EmailField(max_length=40)
section = models.CharField(max_length=25)
def __str__(self):
return self.name
Once the manageStudents model is created, django can use it to create a SQLite table containing the same attributes: name, email, section. To do this, make the migrations:
python manage.py makemigrations manageStudents
and
python manage.py migrate
3 - Creation of the form via the ModelForm class
We will now see how to generate an input form automatically using the ModelForm class, containing the fields:
- name
- section
Let's create a python file named form.py in the manageStudents app and import the ModelForm class from django.forms and the Students class from manageStudent.models and then create a StudentsForm class which will be used to generate the html form :
from django.forms import ModelForm
from manageStudents.models import Students
class StudentsForm(ModelForm):
class Meta:
model = Students
fields = ['name' , 'email' , 'section']
Now we can create the views:
from django.shortcuts import render, redirect
from manageStudents.form import StudentsForm
def index(request):
# testing if there is a sended post request
if request.method == "POST":
# creating a form
form = StudentsForm(request.POST)
# testing if the form is valid
if form.is_valid():
# saving the data form
model_instance = form.save()
# redirect user
return redirect("/students")
else:
# else we create a form without saving any data
form = StudentsForm()
return render(request , 'index.html' , {'form' : form})
Then we configure the urls.py
from django.contrib import admin
from django.urls import path
from manageStudents import views
urlpatterns = [
path('admin/', admin.site.urls),
path('students/' , views.index )
]
Now , we have to code the template file index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>Students management</h2>
<!-- Creating html form -->
<form method="POST" class="post−form">
<!-- adding security tag -->
{% csrf_token %}
<!-- adding form as paragraph (as_p = as paragraph) -->
{{ form.as_p }}
<!-- adding submit button -->
<button type="submit" class="save btn btn−default">Save</button>
</form>
</body>
</html>
Now after starting the server and type the url address: http://127.0.0.1:8000/students/
We will see our nice form appear:
Note
The above form is functional, you can verify that it inserts the data correctly into the database.
4 - Display of data from the Students table
To display the data from the manageStudents_students table, just import the Students class from manageStudents.models:
from manageStudents.models import Students
and add the value: Students.objects.all() to the dictionary:
{ 'form': form , 'dataObject': Students.objects.all()}
Here is the final code of views.py file:
from django.shortcuts import render, redirect
from manageStudents.form import StudentsForm
from manageStudents.models import Students
def index(request):
if request.method == "POST":
form = StudentsForm(request.POST)
if form.is_valid():
model_instance = form.save()
return redirect("/students")
else:
form = StudentsForm()
return render(request , 'index.html' , {'form' : form , 'dataObject' : Students.objects.all()})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>Students management</h2>
<form method="POST" class="post−form">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn−default">Save</button>
</form>
<h3>Student list:</h3>
{% for stud in dataObject %}
Name: {{ stud.name }}<br />
Email: {{ stud.email }}<br />
Section: {{ stud.section }}<br />
-------------------------------<br />
{% endfor %}
</body>
</html>
Now launch the server and insert some data to see the result:
my-courses.net