Django Forms

When one creates a Form class, the most important part is defining the fields of the form. Each field has custom validation logic, along with a few other hooks. Forms are basically used for taking input from the user in some manner and using that information for logical operations on databases. For example, Registering a user by taking input as his name, email, password, etc. Django maps the fields defined in Django forms into HTML input fields. Django handles three distinct parts of the work involved in forms:

  • preparing and restructuring data to make it ready for rendering
  • creating HTML forms for the data
  • receiving and processing submitted forms and data from the client

Note: All types of work done by Django forms can be done with advanced HTML stuff, but Django makes it easier and efficient especially the validation part. Once you get hold of Django forms you will just forget about HTML forms.

Creating Django Forms

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. 

To create a Django form, first create a forms.py inside the app folder.

Python3




from django import forms
  
class GeeksForm(forms.Form):
  
    title = forms.CharField(max_length=200)
    description = forms.CharField(widget=forms.Textarea)
    image = forms.ImageField()


Let’s create a different view function for handling forms and we will map this view function to a different URL. In the above created views.py file import the GeeksForm from the forms.py and create the below function.

views.py

Python3




from .forms import GeeksForm
  
def geeks_form(request):
    context = {}
    context['form'] = GeeksForm
    return render(request, "form.html", context=context)


Map this function to a different URL let’s say we will map this function to the http://127.0.0.1:8000/add/. To do this go to urls.py file of the app and another path for above URL.

urls.py

Python3




from django.urls import path
from . import views
  
urlpatterns = [
    path('', views.geeks_view, name='geeks_view'),
    path('add/', views.geeks_form, name="geeks_form")
]


Django form fields have several built-in methods to ease the work of the developer but sometimes one needs to implement things manually for customizing User Interface(UI). A form comes with 3 in-built methods that can be used to render Django form fields.  

Now let’s make the form.html for rendering our form.

HTML




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


After doing this save all the files and go to http://127.0.0.1:8000/add/ to see the form we created. It should look like this – 

We can also see that our form is validated automatically. We cannot submit an empty form.

Create Django Form from Models

Django ModelForm is a class that is used to directly convert a model into a Django form. To create a form directly for our model, dive into forms.py and Enter the following –

Python3




from django import forms
from .models import GeeksModel
  
class GeeksForm(forms.ModelForm):
  
    class Meta:
        model = GeeksModel
        fields = ['title', 'description', 'image']


Now visit http://127.0.0.1:8000/add/ you will see the same form as above but with less code. 

Both the Django forms we created are similar but the only difference is the save() method. Every ModelForm has a save() method which saves the database object from the data bound to the form. In simpler words we will be able to save the data to our database using the ModelForm only. For this change the view method as follow – 

views.py

Python3




def geeks_form(request):
    if request.method == 'POST':
        form = GeeksForm(request.POST, request.FILES)
  
        if form.is_valid():
            form.save()
            return redirect("geeks_view")
        else:
  
            # uncomment the below line to see errors
            # in the form (if any)
            # print(form.errors)
            return redirect("geeks_form")
    else:
        context = {}
        context['form'] = GeeksForm
        return render(request, "form.html", context=context)


Note: Add enctype= multipart/form-data to our <form> element in our template tag. If we don’t have this then our request.FILES will always be empty and our form will not validate.

 Let’s add some data with our form and see if its get saved in our database or not.

After hitting submit the form gets saved automatically to database. We can verify it from the above GIF.

Refer to the below articles to get more information about Django Forms – 

Python Web Development With Django

Python Django is a web framework that allows to quickly create efficient web pages. Django is also called batteries included framework because it provides built-in features such as Django Admin Interface, default database – SQLite3, etc. When you’re building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Django gives you ready-made components to use.

Similar Reads

Why Django Framework?

Excellent documentation and high scalability. Used by Top MNCs and Companies, such as Instagram, Disqus, Spotify, Youtube, Bitbucket, Dropbox, etc. and the list is never-ending. Easiest Framework to learn, rapid development, and Batteries fully included. Django is a rapid web development framework that can be used to develop fully fleshed web applications in a short period of time. The last but not least reason to learn Django is Python, Python has a huge library and features such as Web Scraping, Machine Learning, Image Processing, Scientific Computing, etc. One can integrate all this with web applications and do lots and lots of advanced stuff....

Django Architecture

Django is based on MVT (Model-View-Template) architecture which has the following three parts –...

Setting up the Virtual Environment

Most of the time when you’ll be working on some Django projects, you’ll find that each project may need a different version of Django. This problem may arise when you install Django in a global or default environment. To overcome this problem we will use virtual environments in Python. This enables us to create multiple different Django environments on a single computer. To create a virtual environment type the below command in the terminal....

Installing Django

We can install Django using the pip command. To install this type the below command in the terminal....

Starting the project

To initiate a project of Django on Your PC, open Terminal and Enter the following command...

Project Structure

A Django Project when initialized contains basic files by default such as manage.py, view.py, etc. A simple project structure is enough to create a single-page application. Here are the major files and their explanations. Inside the geeks_site folder ( project folder ) there will be the following files-...

Creating an app

Django is famous for its unique and fully managed app structure. For every functionality, an app can be created like a completely independent module. For example, if you are creating a Blog, Separate modules should be created for Comments, Posts, Login/Logout, etc. In Django, these modules are known as apps. There is a different app for each task. Benefits of using Django apps –...

Django Views

...

Django URL Patterns

...

Django Models

A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, anything that a web browser can display. Django views are part of the user interface — they usually render the HTML/CSS/Javascript in your Template files into what you see in your browser when you render a web page....

Uploading Images in Django

...

Render a model in Django Admin Interface

In Django, each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL configuration). Every URLConf module must contain a variable urlpatterns which is a set of URL patterns to be matched against the requested URL. These patterns will be checked in sequence until the first match is found. Then the view corresponding to the first match is invoked. If no URL pattern matches, Django invokes an appropriate error handling view....

Connecting Django to different Database

...

Django Templates

...

Django Forms

To tackle the above-said problem Django provides something called Django Models....

More on Django

...

Django Projects

...