Author Profile Altaf Shaikh
Altaf Shaikh

BE Engg | Python Dev | Content Writer | Founder of TeachMeBro | Blockchain Dev | Django

Django- Forms

February 13th 2020   401

What are Django Forms?
What are Django Forms?

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 tutorial, we have successfully created our User model. Let's see what are Forms in Django.

Forms

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.

account
   └── 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 tutorial, we have successfully created forms in Django. So in the next tutorial, we will see what are Views in Django.