What are Django Forms?

What are Django Forms?

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Django Forms

In this tutorial, we will learn what are Forms in Django and how to use forms.py to connect with models to directly save the result into the database table.

So in our previous section, we have successfully created our User model. Let's see what are Forms in Django.


In Django, With forms we will have absolute power over our interface -- we can do almost anything we can imagine! Creating forms in Django is really similar to creating a model. Here again, we just need to inherit from Django class and the class attributes will be the form fields.

The nice thing about Django forms is that we can either define one from scratch or create a ModelForm which will save the result of the form to the model.

Cool, that's exactly what we want to do, we will create a form for our "User" model. The forms have their own file forms.py. We need to create a file with this name in the account/ directory.

   └── forms.py

OK, let's open it in the code editor and type the following code:

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms

class UserCreateForm(UserCreationForm):
    name = forms.CharField(label="Full Name", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': ''}))
    phone_no = forms.CharField(label="Mobile No", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': ''}))

    class Meta:
        fields = ("name","username", "email","phone_no", "password1", "password2")
        model = User

    #to override the default label
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["username"].label = "User Name"
        self.fields["email"].label = "Email address"

We need to import Django forms first (from django import forms), UserCreationForm from (from django.contrib.auth.forms import UserCreationForm) and our User model (from django.contrib.auth.models import User).

UserCreateForm, as you probably suspect, is the name of our form. We need to tell Django that this form is a UserForm(so Django will do some magic for us) -- UserCreationForm is responsible for that.

Next, we have class Meta, where we tell Django which model should be used to create this form (model = User).

Finally, we can say which field(s) should end up in our form. In this scenario, we want the following fields name, username, email,phone_no, password1, password2 which are already defined by Django.

And that's it! All we need to do now is use the form in a view and display it in a template.

In this section, we have successfully created forms in Django. So in the next section, we will see what are Views in Django.

Share this