Setting a maximum length

One of the most common validation needs is to check that a field is of a certain size. For good measure, we should improve our ContactForm to limit the subject to 100 characters. To do that, just supply a max_length to the CharField, like this:

from django import forms 
 
class ContactForm(forms.Form): 
    subject = forms.CharField(max_length=100) 
    email = forms.EmailField(required=False) 
    message = forms.CharField(widget=forms.Textarea) 

An optional min_length argument is also available.

Get Mastering Django: Core now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.