Django - limit the number of characters allowed to enter in a text field

Here are my models.py:

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

and here are 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 as many characters as he wants in the text field, and he will receive an error message after the user sends the text. I want the user to be able to enter only 200 characters, and when he reaches 200 characters, the text box does not allow the user to enter anything else (even before he sends it). How can i do this?

+4
source share
1 answer

Use the attribute maxlengthfor your HTML element textarea.

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

Source: https://habr.com/ru/post/1545157/


All Articles