Create Model Form in Django

In this Python tutorial, I will show how to create model form in Django, where you will build a small Django project that will allow users to log in through a form.

You will learn about the class ModelForm which is used to create a form based on the provided model. Also, you will learn about the nested class called Meta in the ModelForm class.

What is Model Form in Django?

Whenever you visit a new website, to access the content of the website first you need to log in and for that, a website shows you the login page to fill in the login details or some kind of input field to accept the login details.

You can call the login form to this page containing the input field that accepts the user data. Now if you are a beginner at Django or you may have done some work with Django, then you have created the models in the file models.py of your Django app.

This model represents the database table. So Django allows you to create a form using the model in a quick way.

  • To create a form based on the model, Django provides a class called ModelForm. There are other classes for creating different kinds of forms but the ModelForm is the core class.
  • So in simple words, A ModelForm takes the Django model and automatically creates the form from that model, which also helps in simplifying the process of data submission and data validation.

So in which kind of application, the form is used, the model form is used in the database-driven application which means the application required to store or persist the data in the database, that kind of application uses the form.

Let’s start with real-world examples where you will create simple login forms that you see on different websites.

Create Model Form in Django Project Set Up

First up the Django project by following the below steps

Create a virtual environment using the below command.

python -m venv form_env

Activate the environment using the below command.

form_env\Scripts\activate

Install the latest version of the Django.

pip install django
Create Model Form in Django Project Set Up

Create a Django project named ‘django_form’ using the below command.

django-admin startproject django_form

Change the directory to the django_form.

cd djnago_form

Create a new app called form_app using the below command.

python manage.py startapp form_app
Project Set Up Create Model Form in Django

Open the Django project in your preferred IDE such as Visual Studio Code.

Create Model Form in Django Creating Model

First, add the Django app ‘form_app’ into the INSTALLED_APP section of the setting.py file of the Django project ‘django_form’.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'form_app'
]
Create Model Form in Django Adding App

Now create a model named User in the file models.py of your Django app ‘form_app’ and add the following lines of code.

from django.db import models


class User(models.Model):
    name = models.CharField(max_length=70)
    email = models.EmailField(max_length=100)
    password = models.CharField(max_length=100)

    def __str__(self):
        return self.name
Create Model Form in Django Model User

The model User has three fields name, email and password with a function that returns the name of the user. Remember these fields.

Let’s create a simple login form based on the model User, so for that create a new file called login_form.py under the Django app ‘form_app’ and add the following lines of code in that file.

from django.forms import ModelForm
from .models import User

class LoginForm(ModelForm):
    class Meta:
        model = User
        fields = '__all__'
Create Model Form in Django

In the above code at line 1 importing the class ModelForm from the module django.forms, this class creates the form automatically based on the given model. Then at line 2 import the model User from the python file models.py.

After that, from lines 4 to 7 define the LoginForm class that inherits the ModelForm which means the LoginForm class will automatically create a form field based on the fields specified in the model, so in our case model is the User.

  • Then in line 5, there is a Meta class and this is the nested class within ModelForm. The Meta class gives additional information or metadata on how the form should be structured.
  • The first most common information is which model should be used to create a form and the second is which fields from the model should be included in the form.
  • So in our case, in line 6 it is specified that use the model User using model=User and use all the fields from the model in line 7 using fields=’__all__’. You can also specify the required field only using fields = [‘name’, ‘password’]. So to include only a specific field create list containing the field which is defined in the model.

Don’t be confused with class Meta it holds the main data, the class Meta only instructs how ModelForm is set up and displays the form based on the given model and the details in the Meta class.

Basically, the above code creates a LoginForm based on the provided model User which is going to create a form that will contain an input field which corresponds to the field defined in the model User.

Create Model Form in Django Creating View

Now you know how to create a form based on the model, let’s render this form and understand how it shows the input field or how the form is validated. Once you define the form how or where you are going to render or process the data of the form?

For that, you can use the defined form (LoginForm) in the view to render the form or process the data. So open the file views.py of your Django app ‘form_app’ and add the following lines of code.

from django.shortcuts import render, redirect
from .login_form import LoginForm

def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = LoginForm()
    return render(request, 'login.html', {'form': form})


def home(request):
    return render(request, 'home.html')
Create Model Form in Django View Login

In the above code, from lines 1 to 2 import the required function or class from the django.shortcuts and directory login_form.

  • Then from lines 4 to 12, a function named ‘login’ is defined which handles both the display of the login form and the submission of that form. The function login accepts the parameter request which represents the current web request.
  • After this, from lines 5 to 9 handling the form submission, first, it is checked whether the request is POST or not. If the request is equal to POST it means the form has been submitted by the user, then a form instance is created by passing the request.POST to the LoginForm.
  • Then again line 7, check if the form data is correct according to the rules defined by the LoginForm using form.is_valid(), but here you should notice that we haven’t defined any rules while defining the form Login, the rules in the form are automatically defined.
  • If the form data is valid, then the function save() is called on the instance form to save the form data at line 8. Then after saving the form, the user is redirected to another page which is called the home page using redirect(‘home’).

Lines 10 and 11 are executed when the request is not a POST method so in this case, an empty form is created to be displayed using form = LoginForm().

Finally rendering the form at line 12, the function render() is used to display the template ‘login.html’ that we will create soon. To display the form on the template, the form is passed as context to the template as {‘form’: form} within the render function.

Overall the above code creates a view whenever the user visits the website it shows the login form and when the user fills the form and submits it, the view processes the submitted data and if the submitted data is correct, then the user is redirected to another template or page which called home in this case.

This is how to display form and process data using the view in Django.

Create Model Form in Django Creating Templates

Now let’s create a template login.html in the new folder called templates under your Django app ‘form_app’ and add the following lines of code in that template file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Form</title>
</head>
<body>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Submit</button>
    </form>

</body>
</html>
Create Model Form in Django Creating Templates

In the above code from lines 9 to 13 rendering the Django form and the following things are done:

  • To render the form, the <form method = “post”></form> tag is used, the method or it is called attribute defines the method that will used when the form is submitted. In this case, when the user fills in and submits the form, the data will be sent using the HTTP ‘post’ method.
  • Then on line 10 Django template tag {% csrf_token %} is used to protect against CSRF attacks which stands for Cross-Site Request Forgery. Using the CSRF token Django makes sure that any POST request that is sent or coming to the view that handles the form has the correct CSRF token.
  • This process makes sure that the form data that is submitted, is from the site itself and it is not coming from any third party such as malicious attackers or data is not tempered.
  • At line 11, rendering the form field using the {{ form.as_p }} where the method .as_p is renders the form field which is surrunded by the <p> tag. So that each field will be rendered in the next line with its label.

Finally, at line 12 a button with a type equal to ‘submit’ is specified, after filling out the form user clicks on this submit button to send the form data using the HTTP ‘post’ method, and remember this request is received by the view called login that you have defined above.

Create Model Form in Django Defining URLs

But how the request is passed to the view, and to pass the request to a specific view, there is something in Django that is called URLs.

Now create a urls.py file in your Django app ‘form_app’ and add the following lines of code.

from django.urls import path
from . import views

urlpatterns = [
    path('login/', views.login, name='login'),
    path('home/',views.home, name='home'),
]
Create Model Form in Django Defining App URLs

If you look at line 6, the path for the view home, home view and template is not created yet, so let’s create them.

Create a new template named ‘home.html’ in the folder ‘templates’ and add the following line of code that simply shows the text ‘You are logged in’.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home Page</title>
</head>
<body>
    <h4>You are logged in</h4>
</body>
</html>
Template Home Create Model Form in Django

Also, open the file views.py of your Django app ‘form_app’ create a view function named home and add the following lines of code.

def home(request):
    return render(request, 'home.html')
View Home Create Model Form in Django

After this also set up the urls.py file of your Django project ‘django_form’ by adding the following lines of code.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('form_app.urls'))
]
Create Model Form in Django Defining Project URLs

Finally, migrate the model ‘User’ into a database that you have created in the above section. So use the below command in your terminal one by one.

python manage.py migrate
python manage.py makemigrations
python manage.py migrate

After migrating the model User, run the below command to start the Django server.

python manage.py runserver

and go to the URL ‘http://127.0.0.1:8000/login/‘ you see the login page as shown below.

Create Model Form in Django Login Page

Fill out the form and click on the submit button as shown in the below picture.

Filling Form Create Model Form in Django

After submitting the form, it redirects to you the home page showing the message ‘You are logged in’ as shown in the below picture.

Home Page Create Model Form in Django

You have successfully created the login form in Django using the ModelForm class of Django.

Conclusion

In this Python tutorial, you learned how to create a model form in Django using the ModelForm class of Django. This ModelForm takes the model and automatically creates the form containing the input field which corresponds to the field specified in the model. Additionally, you created a Django project to show the login form.

You may like to read: