Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Django Model Forms – Implement Model Forms in Django

Django Model Forms

In this article, we learn about Django model forms and how to connect them with the concept of models.

Prerequisites for Django Model Forms

Before diving into Model Forms, we should be familiar with Django Forms and their usage. So if you are new to it, do check out our Django forms article before moving forward.

If you are already familiar with Django Forms, then lets get started!!

Why Model Forms?

Forms make sense only when we are saving the form entries submitted by the users. Now to store them, we will require some database. This is where Model Forms comes into the picture.

Django Model Forms provides a way to link the data submitted by the client through the form to a Data Model created to store the entry.

Using ModelForm, we can efficiently perform the above task without writing much code.

Hands-on with Django Model Forms

In this section, we will learn to code all the parts required to create a Model Form.

1. Coding a Model in models.py

In models.py, create a model FormModel and add the following fields into it.

class FormModel(models.Model):
    name = models.CharField(max_length = 80)
    age = models.IntegerField()
    address = models.TextField()

    class Meta:
        ordering = ['name'] 

    def __str__(self):
        return f"Form by {self.name}"

Here, we are using Textfield, since the address can be long enough. Do check out the Django Models article for a better understanding of models.

After the model form is added, run the migrations as shown below to create the DB table

python manage.py migrate
python manage.py makemigrations

2. Coding a Model Form in forms.py

Now in the forms.py, create a form as demonstrated below:

Import FormModel from .models

from .models import FormModel

Then add the code for Form .

class Form(forms.ModelForm):
    class Meta:
        model = FormModel
        fields =('name','age','address',)
  • Class Meta links the Form above to the model we created to store form data.
  • Mention the Model Fields which will be displayed to the user in the form.

3. Coding the FormView in views.py

In Views.py, add the following code for FormView.

def FormView(request):
    if request.method == 'POST':
        form = Form(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse('Your review has been taken')
 
    else:
        form = Form()
        context = {
            'form':form,
        }
    return render(request, 'app_name/form.html<path to template>', context)

If the form is valid, form.save() directly saves the form into the DB itself.

With Model Form, Django will take care of everything. All the form entries will be saved to the linked FormModel DB automatically.

4. Coding the Form Template File.

The only thing left now is to create a Form Template to display the form to the user.

In the namespaced templates’ folder, create a form.py template file.

<form method='post'>
    {% csrf_token %}
    {{form.as_p}}
    <input type="submit" value = "submit">
</form>

That’s it, our HTML file is ready! Now we just have to create a new path to the FormView in urls.py

path('form/model', FormView, name='FormView'),

That’s it guys!! The coding part is done, let us now fire up the server.

Implementation of Model Forms

Start the server from the terminal/cmd.

Form
Form

Fill up the fields and click on submit.

Form Submission
Form Submission

Let us now check whether the form is saved. Go to the admin site.

Form Model
Form Model

Wow!! That’s it, the entry has been saved. See how simple it is to implement Django Model Forms.

Conclusion

That’s it, coders! This was all about Django Model Forms and how you can implement them with the Django Models.

Do check out the Django Forms tutorial for a better understanding of Forms. See you in the next article! Keep practicing!