Django Forms class

Posted under » Django on 10 Jun 2021

A sample form template may look like this

<form action="/your-name/" method="post">
 <label for="your_name">Your name: </label>
 <input id="your_name" type="text" name="your_name" value="{{ current_name }}">
 <input type="submit" value="OK">
</form>

Let's begin by creating a "forms.py"

from django import forms

class NameForm(forms.Form):
 your_name = forms.CharField(label='Your name', max_length=100)

If database model is involved, read this.

This defines a Form class with a single field (your_name). The field’s maximum allowable length is defined by max_length. This does two things. It puts a maxlength="100" on the HTML <input> (so the browser should prevent the user from entering more than that number of characters in the first place). It also means that when Django receives the form back from the browser, it will validate the length of the data.

A Form instance has an is_valid() method, which runs validation routines for all its fields. When this method is called, if all fields contain valid data, it will:

It, will look like:

<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" maxlength="100" required>

Note that it does not include the <form> tags, or a submit button. We’ll have to provide those ourselves in the template.

Next we edit the views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import NameForm

def get_name(request):
 # if this is a POST request we need to process the form data
 if request.method == 'POST':
  # create a form instance and populate it with data from the request:
  form = NameForm(request.POST)
  # check whether it's valid:
  if form.is_valid():
   # process the data in form.cleaned_data as required
   # ...
   # redirect to a new URL:
   return HttpResponseRedirect('/thanks/')

 # if a GET (or any other method) we'll create a blank form
 else:
  form = NameForm()
 return render(request, 'name.html', {'form': form})

Note that in the views.py, you have to import "from .forms import NameForm" and render "form = NameForm()".

Finally, we do the 'name.html' template.

<form action="/your-name/" method="post">
 {% csrf_token %}
 {{ form }}
 <input type="submit" value="Submit">
</form>

Form class is about forms layout. You can enhance forms with the forms widget.

Proceed to learn about creating a working form ».

More about Django Form classes »

There are 2 types of form, bound (with data) and unbound forms.

Trivia : In Cakephp, we call this form helper

You can make your forms dev easier and nicer with Crispyforms Bootstrap5

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data