84👍
✅
As of Django 1.2 this can be done by validators at model level, as explained here:
https://docs.djangoproject.com/en/stable/ref/validators/
from django.core.validators import MaxLengthValidator
class Comment(models.Model):
comment = models.TextField(validators=[MaxLengthValidator(200)])
Since Django 1.7, you can use max_length
which is only enforced in client side. See here
12👍
You can enforce a max length for a TextField by defining a CharField with a Textarea widget like this:
class MyClass(models.Model):
textfield = models.TextField()
class MyForm(forms.ModelForm):
textfield = forms.CharField(
max_length = 50,
widget = forms.Textarea
)
class Meta:
model = MyClass
fields = ('textfield',)
- [Django]-Django signals vs. overriding save method
- [Django]-Django – Where are the params stored on a PUT/DELETE request?
- [Django]-Django Reverse with arguments '()' and keyword arguments '{}' not found
0👍
No need to import MaxLengthValidator from validators for Django 2.x
from django.db import models
class Comment(models.Model):
comment = models.TextField(max_length=200)
- [Django]-How can I handle Exceptions raised by dango-social-auth?
- [Django]-How can I retrieve a list of field for all objects in Django?
- [Django]-What is the best location to put templates in django project?
Source:stackexchange.com