Django Forms - How To Use Django Forms

March 6, 2023, 10:23 p.m.

django python

Django forms provide a way to handle HTML form data in a more secure and efficient manner. With Django forms, you can easily create and handle forms, validate user input, and respond to errors.

To use Django forms, you first need to define a form class in your Django application. This class will inherit from the django.forms.Form class, and you can add fields to the form using various field types provided by Django, such as CharField, IntegerField, BooleanField, and so on.

If you haven't install python and django you can start from here Installing python and django

For Quick Setup

Create a virtual environment

python -m venv env

Activate virtual environment

source env/bin/activate

Installing Django

Install python using pip command
pip install django

Creating your first Project

django-admin startproject projectname

Creating your first App

Change to project directory: "cd projectname"

django-admin startapp appname

you see app have its own file structure, hence it is independent of the project. To work with app we need to include it in project

projectname/projectname/settings.py

# Application definition
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "whitenoise.runserver_nostatic",
    "django.contrib.sitemaps",
    "appname", # <-- add this 
]

Create Form

projectname/appname/forms.py

from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(label='Your name', max_length=100)
    email = forms.EmailField(label='Your email')
    message = forms.CharField(label='Your message', widget=forms.Textarea)

In this example, the ContactForm class defines three fields: name, email, and message. Each field has a label that will be used to render the form in HTML, and an optional widget that will determine how the field is rendered.

Create View

Once you have defined your form class, you can use it in your Django views to handle user input. When a user submits a form, you can create an instance of your form class with the submitted data, and then validate the form using the is_valid() method. If the form is valid, you can access the cleaned data using the cleaned_data attribute of the form.

Here's an example of a Django view that handles a form submission:from django.shortcuts import render

projectname/appname/views.py

from .forms import ContactForm

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # process form data here
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            message = form.cleaned_data['message']
            # do something with the form data
    else:
        form = ContactForm()
    return render(request, 'contact.html', {'form': form})

 

In this example, the contact view checks whether the request method is POST (indicating a form submission), creates an instance of the ContactForm class with the submitted data, and then checks whether the form is valid. If the form is valid, the view extracts the cleaned data from the form using the cleaned_data attribute, and then processes it as needed.

Create Templates

Create a directory called templates within your Django app.

Create an HTML file called contact.html within the templates directory:

<!DOCTYPE html>
<html>
<head>
    <title>My Django App</title>
</head>

<body>
    <form method="POST">
   {% csrf_token %}
   {{ form }}
   <input type="submit" value="submit"/>
   </form>
</body>
</html>

Finally, the view renders a response using a template that includes the form. The form fields will be rendered with the appropriate HTML tags and attributes based on the field types and widgets you defined in your form class.

author image

bracketcoders

A learing portal for your coding interest.

View Profile