Handling Forms in Django

Forms are a crucial part of any web application — they let users input and submit data. In Django, form handling is clean, secure, and straightforward thanks to its powerful django.forms module.


✅ 1. What Are Forms in Django?

Django provides a Form class to handle form creation, validation, and processing. Forms can be created in two main ways:

Django Forms – created manually using Python classes.

ModelForms – automatically generate forms from database models.


๐Ÿงฑ 2. Creating a Basic Django Form

from django import forms

class ContactForm(forms.Form):

    name = forms.CharField(max_length=100)

    email = forms.EmailField()

    message = forms.CharField(widget=forms.Textarea)


๐Ÿงพ 3. Using the Form in a View

from django.shortcuts import render

from .forms import ContactForm

def contact_view(request):

    if request.method == 'POST':

        form = ContactForm(request.POST)

        if form.is_valid():

            # Process form data

            name = form.cleaned_data['name']

            email = form.cleaned_data['email']

            message = form.cleaned_data['message']

            # Do something (e.g., send email or save to DB)

            return render(request, 'thank_you.html')

    else:

        form = ContactForm()

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


๐Ÿ–ฅ️ 4. Rendering the Form in Template

<!-- contact.html -->

<form method="post">

  {% csrf_token %}

  {{ form.as_p }}

  <button type="submit">Send</button>

</form>

{{ form.as_p }} renders each field wrapped in a <p> tag.

{% csrf_token %} protects against Cross-Site Request Forgery.


๐Ÿ” 5. ModelForm Example

Use ModelForm when the form fields directly relate to a database model.

# models.py

from django.db import models

class Feedback(models.Model):

    name = models.CharField(max_length=100)

    comments = models.TextField()

# forms.py

from django.forms import ModelForm

from .models import Feedback

class FeedbackForm(ModelForm):

    class Meta:

        model = Feedback

        fields = ['name', 'comments']


๐Ÿงช 6. Form Validation

Django automatically validates required fields and data types. You can also write custom validation:

def clean_email(self):

    email = self.cleaned_data['email']

    if not email.endswith('@example.com'):

        raise forms.ValidationError("Only @example.com emails are allowed.")

    return email


๐Ÿ”š Conclusion

Django’s form system makes it easy to:

Build and display forms

Validate and clean user input

Bind form data to models using ModelForms

Learn Fullstack Python Training Course

Read More:

Django REST Framework Tutorial

Connecting Python with MySQL

PostgreSQL Integration with Django

Introduction to ORM in Django

Visit Quality Thought Training Institute

Get Direction

 

 

Comments

Popular posts from this blog

DevOps vs Agile: Key Differences Explained

Regression Analysis in Python

Top 10 Projects to Build Using the MERN Stack