Handling Forms In Flask And Django

Handling Forms in Flask and Django

Python is a versatile language that facilitates web development through numerous frameworks. ‘Flask’ and ‘Django’ are among the most favored web frameworks for Python. They streamline complex tasks such as URL routing, template rendering, and form handling. This article provides a detailed perspective on handling forms in Flask and Django. Through examples and concise explanations, you’ll grasp the fundamentals and more advanced aspects of this critical task in web development.


Handling Forms In Flask And Django
Handling Forms In Flask And Django

Understanding Forms in Web Development

Web forms serve as the primary interaction point between users and web applications – be it signing up for online accounts or entering credit card details for online purchases. Forms allow users to submit data, which the web application processes and responds accordingly.

In Python’s Flask and Django, form handling is a step-by-step process including: creating the form, rendering it to the user, receiving and processing submitted data and providing an appropriate response.

Handling Forms in Flask

Flask, as a lightweight and flexible Python framework, offers straightforward ways to handle web forms.

Installation and Setup

Before creating forms in Flask, it is advisable to install Flask-WTF, an extension that simplifies form handling. To install Flask-WTF, use the following pip command in your terminal:

pip install flask-wtf

With Flask-WTF installed, you can begin creating a simple form.

Creating a Form

The first step is to define the form as a class, which inherits from FlaskForm. Each class variable represents a field in the form. For example, to create a form with a username and password field, you can use the following code:

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField

class LoginForm(FlaskForm):
    username = StringField('Username')
    password = PasswordField('Password')
    submit = SubmitField('Sign In')

Template Rendering

The next step is to render this form to users, typically by sending it to a template via a route. Here is an example in which a route function creates an instance of LoginForm and passes it to a template:

from flask import render_template
from forms import LoginForm

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    return render_template('login.html', form=form)

In the template, Flask’s Jinja2 templating engine will generate HTML from the form instance. For instance, ‘login.html’ might look like this:

<form method="POST">
    {{ form.hidden_tag() }}
    {{ form.username.label }} {{ form.username() }}
    {{ form.password.label }} {{ form.password() }}
    {{ form.submit() }}
</form>

Form Validation and Processing Data

When a user submits a form, the system must validate and process the input data. Flask-WTF provides a convenient method for validating form data:

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        return 'Form Successfully Submitted!'
    return render_template('login.html', form=form)

Handling Forms in Django

Django, a high-level Python web framework, automates much of the complex aspects of form handling.

Setting Up

To handle forms in Django, you should install Django through pip:

pip install django

Following this, create a new Django project using the django-admin tool:

django-admin startproject myproject

Now, you are ready to create your form.

Creating a Form

Just like in Flask, forms in Django are defined as classes. Django’s Form class is typically used as a base class for all forms:

from django import forms

class CommentForm(forms.Form):
    name = forms.CharField(label='Your Name')
    comment = forms.CharField(widget=forms.Textarea)

Rendering the Form

Django provides several ways to render a form in a template. The simplest method involves creating a form instance in a view and passing it to the template:

from django.shortcuts import render
from .forms import CommentForm

def comment(request):
    form = CommentForm()
    return render(request, 'comments.html', {'form': form})

In the template, Django helps to generate the HTML:

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

Processing Form Data and Validation

Within Django, processing form data involves making a POST request. The is_valid() method validates the form data and provides cleaned data if validated:

def comment(request):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')
    else:
        form = CommentForm()

    return render(request, 'comments.html', {'form': form})

FAQs on Handling Forms in Flask and Django

1. What is Flask? Flask is a lightweight and flexible web framework for Python.

2. What is Django? Django is a high-level, built-in feature-rich web framework for Python.

3. What is Flask-WTF? Flask-WTF is an integrated Flask extension that simplifies form handling.

4. How are web forms defined in Flask and Django? Web forms in Flask and Django are defined as classes, with each class variable acting as a field in the form.

5. How can form data be validated in Flask and Django? Form data can be validated in Flask with the validate_on_submit() method and in Django with the is_valid() method.

By comprehending this guide, you can create, render, validate and process forms in Flask and Django with ease. These two frameworks, while similar in many aspects, offer unique tools and conventions that provide developers with flexible and efficient methods for handling web forms.

Share this article:

Leave a Comment