Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Form Fields in Django

Introduction

In Django, forms are used to handle user input. They can be used to validate data and handle HTML form fields easily. In this tutorial, we will cover various types of form fields available in Django and how to use them effectively.

Creating a Form

To create a form in Django, you need to create a class that inherits from forms.Form. Here is an example:

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(widget=forms.Textarea, label='Your Message')

Form Fields

Django provides several built-in form fields. Here are some of the most commonly used ones:

CharField

The CharField is used for input of text. You can specify the maximum length of the field:

name = forms.CharField(label='Your Name', max_length=100)

EmailField

The EmailField is used for email input, and it includes validation to ensure a valid email address is entered:

email = forms.EmailField(label='Your Email')

Textarea

The Textarea widget is used for multi-line text input, typically for longer messages:

message = forms.CharField(widget=forms.Textarea, label='Your Message')

BooleanField

The BooleanField is used for true/false input, typically rendered as a checkbox:

subscribe = forms.BooleanField(label='Subscribe to newsletter', required=False)

DateField

The DateField is used for date input, and it can be rendered with a date picker:

birthday = forms.DateField(label='Your Birthday')

ChoiceField

The ChoiceField is used for selecting one option from a list of choices:

CHOICES = [('male', 'Male'), ('female', 'Female')]
gender = forms.ChoiceField(choices=CHOICES, label='Select Gender')

Rendering the Form

To render the form in a template, you need to pass the form instance to the context and use the template syntax to display the form:

from django.shortcuts import render
from .forms import ContactForm

def contact_view(request):
    form = ContactForm()
    return render(request, 'contact.html', {'form': form})

In your template (contact.html), you can render the form like this:

{% load static %}



    Contact Us


    

Contact Us

{% csrf_token %} {{ form.as_p }}