Django — Creating Model Forms

Model forms in Django are a seamless way to create web-based forms with the ability to store data in the database.

Assuming your Django project is created and you have created an application folder (if not, see the documentation for the setup process), let’s get started creating a model form.

Firstly, we have created a simple model in models.py for a ‘client’ with 2 name fields. The ‘str’ function enables us to view the model outputs cleanly in the admin panel.

from django.db import models

class Client(models.Model):
first = models.CharField(max_length=50)
surname = models.CharField(max_length=50)


def __str__(self):
return f'{self.first}, {self.surname}'

Once saved and migrated, we will now create a forms.py file in our application directory (sits alongside models, views etc).

Here we will import forms, model form and the relevant model we have created (‘Client’). The class of ClientForm is created (ensure you keep congruency with the model name) where we define the model and the fields. In this case we will want both name fields (‘__all__’).

from django import forms
from django.forms import ModelForm
from .models import Client


class ClientForm(forms.ModelForm):
class Meta:
model = Client
fields = '__all__'

We’ll now head over to the views.py file and write the code that will process the data, save it and redirect us back to a home page. Ensure that ‘redirect’ is imported via django.shortcuts.

def client(request):
form = ClientForm From 'forms.py'

if request.method == 'POST':
form = ClientForm(request.POST)
if form.is_valid(): If completed:
form.save() Save the form
return redirect('/') Back To Home

context = {'form': form} Use in template
return render(request, 'client.html', context)

To render this out on a web-page, we’ll (1) write a url path in our application’s urls.py file:

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

…and (2) create a ‘client.html’ file in a templates folder:

<h1> Client Data </h1>
<hr>

<form method="post">

{% csrf_token %} Required to process form
{{ form }} From our context variable

<input type="submit">

</form>

Our client URL (http://127.0.0.1:8000/client/) will now render and display the basic form below.

We can input data which will be saved (& viewed in the admin panel) and upon completion of the form will get redirected back to our home page.

For more information and if you get stuck, visit the official documentation on ModelForms here.

Python | Finance