How can I programmatically get the max_length of a Django model field?

Let's say I have a Django class something like this:

class Person(models.Model): name = models.CharField(max_length=50) # ... 

How can I programmatically get the max_length value for the name field?

+49
python oop django django-models
01 Dec '09 at 21:56
source share
2 answers

Person._meta.get_field('name').max_length will give you this value. But using _meta suggests that this is something you should not do under normal use.

Edit: as Carl noted, this naming is misleading, and it is perfectly acceptable to use it: http://www.b-list.org/weblog/2007/nov/04/working-models/

+67
Dec 01 '09 at 22:08
source share

Ben-James answer is a good answer, but I think it is simpler and more understandable:
1. In the template:
{{form.name.field.max_length}}

2. In python code (for example, in a view)
form.name.field.max_length

+3
Jul 03 '15 at 17:21
source share



All Articles