SilentDev
SilentDev

Reputation: 22747

Django - Limit the amount of characters allowed to be typed into a textbox

Here is my models.py:

class Blog(models.Model):
    blogPost = models.CharField(max_length=200)

and here is my forms.py:

class BlogForm(forms.ModelForm):
    class Meta:
        model = Blog
        fields = ['blopPost']
        widgets = { 'blogPost' : forms.Textarea(attrs={'rows':5, 'cols':90}) }

Currently, the user can enter in as many as characters as he wants into the textbox and he will only receive an error message after the user submits the text. I want it so that the user can only type in 200 characters and the moment he reaches 200 characters, the textbox does not allow the user to type in anything else (even before he submits it). How would I go about doing this?

Upvotes: 5

Views: 6700

Answers (1)

Matt
Matt

Reputation: 10312

Use the maxlength attribute on your textarea HTML element.

class BlogForm(forms.ModelForm):
    class Meta:
        model = Blog
        fields = ['blogPost']
        widgets = {
            'blogPost' : forms.Textarea(attrs={
                'rows': '5',
                'cols': '90',
                'maxlength': '200',
            }),
        }

Upvotes: 10

Related Questions