Saturday, November 16, 2024
Google search engine
HomeLanguagesHow to create a form using Django Forms ?

How to create a form using Django Forms ?

Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. This post revolves around how to create a basic form using various Form Fields and attributes. Creating a form in Django is completely similar to creating a model, one needs to specify what fields would exist in the form and of what type. For example, to input, a registration form one might need First Name (CharField), Roll Number (IntegerField), and so on.
 

Creating a form using Django Forms

Illustration of Django Forms using an Example. Consider a project named neveropen having an app named Lazyroar. 

Refer to the following articles to check how to create a project and an app in Django. 
 

In your Lazyroar app make a new file called forms.py where you would be making all your forms. To create a Django form you need to use Django Form Class. Let’s demonstrate it.
 

In your forms.py Enter the following, 

Python3




from django import forms
 
# creating a form
class InputForm(forms.Form):
 
    first_name = forms.CharField(max_length = 200)
    last_name = forms.CharField(max_length = 200)
    roll_number = forms.IntegerField(
                     help_text = "Enter 6 digit roll number"
                     )
    password = forms.CharField(widget = forms.PasswordInput())


Let’s explain what exactly is happening, left side denotes the name of the field and to the right of it, you define various functionalities of an input field correspondingly. A field’s syntax is denoted as 

Syntax : 

Field_name = forms.FieldType(attributes)

Now to render this form into a view, move to views.py and create a home_view as below. 

Python3




from django.shortcuts import render
from .forms import InputForm
 
# Create your views here.
def home_view(request):
    context ={}
    context['form']= InputForm()
    return render(request, "home.html", context)


In view, one needs to just create an instance of the form class created above in forms.py. Now let’s edit templates > home.html 

HTML




<form action = "" method = "post">
    {% csrf_token %}
    {{form }}
    <input type="submit" value=Submit">
</form>


All set to check if the form is working or not let’s visit http://localhost:8000/ 

create-django-form

The form is working properly but visuals are disappointing, Django provides some predefined ways to show forms in a convenient manner. In templates, the following will modify the inputs as, 

One can modify these settings also and show fields as he wants using {{ form.field_name }} but this may alter the normal process of validation if some field is empty and hence needs extraordinary care. More – Django Forms

RELATED ARTICLES

Most Popular

Recent Comments