Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 778
SilentDev Avatar asked Jun 19 '14 03:06

SilentDev


1 Answers

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',
            }),
        }
like image 184
Matt Deacalion Avatar answered Jan 03 '23 12:01

Matt Deacalion