django forms getting started

django forms getting started

django forms are allow user to enter the data and send it to the server to use it further. django forms are powerful and generates the html form elements which simplifies developers life easy.

Basics of HTML form

Let's understand the basics of HTML form from below example.

<form action="/contact-us/" method="POST" enctype="multipart/form-data">
   <label>First Name</label>
   <input name="first_name" value="" />
   <label>Last Name</label>
   <input type="text" name="last_name" value="" />
   <label> Message </label>
   <textarea name="message"></textarea>
   <input type="submit" value="Submit" />
  • action: It specifies where to send the form-data when a form is submitted
  • method:  Type of request when the form is submitted
  • enctype: encrypion type for the form data. "multipart/form-data" allows us to send the text and files data aswell.
  • For more details on HTML forms visit 

Django Forms and it's usage

In the above example we have written html code for the form. By using django forms we can simplify it with django form template tags like below. Let's write code to save the contact info the database. We will not be creating the django app from the scratch but we will write model and view and template and urls for the functionality.


from django.db import models

class ContacIfo(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    message = models.TextField()

    def __str__(self):
       return self.first_name


from django import forms
from .models import ContacIfo

class ContactInfoForm(forms.ModelForm):
    class Meta:
        model = ContacIfo
        fields = ('first_name', 'last_name', 'message')


from .forms import ContactInfoForm
from django.http import HttpResponse
from django.shortcuts import render

def create_contact_info(request):
    if request.method == 'POST':
       form = ContactInfoForm(request.POST)
       if form.is_valid():
           return HttpResponse("Saved Contact info.") 
       form = ContactInfoForm()
    context = {'form': form}
    return render(request, 'template.html', context)

from django.urls import path

from . import views

urlpatterns = [
# ....
    path('contact-info/', views.create_contact_info, name='contact_info'),
# ....

# template.html

  <title>Create Contact Info</title>
    <form action="{% url 'contact_info' %}" method="POST" enctype="multipart/form-data">
      {% csrf_token %}
      <input type="submit" value="Submit" />

Above code is used to save the contact info on the database. In the previous articles we have seen the usage of views and urls and templates if not you check the course Django. Let's get back to django forms usage.

  • Django forms are two types 1. Model forms (i.e "forms.ModelForm") and 2. Forms (i.e "forms.Form")
  • "forms.ModelForm" more advantages over the "forms.Form" like we can save the object in the database directly using save method of "forms.ModelForm" but, it's not available for "forms.Form".
  • "{% csrf_token %}" in template will create a csrfmiddleware token that used for security protection. It's must for POST requests but it's not needed for GET requests.
  • Django forms comes with inbuilt validations on the form fields,  "is_valid()" method is used to validate the correctness of the form data.

It's just basic start for the django forms usage. Let's learn more about django forms in the next article. You can find the above project code at my github account "django forms getting started".


Support Me on Patreon