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

PythonDjangoDjango ModelsOop

Python Problem Overview


Say I have a Django class something like this:

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

How can I programatically obtain the max_length value for the name field?

Python Solutions


Solution 1 - Python

Person._meta.get_field('name').max_length will give you this value. But having to use _meta suggests this is something you shouldn't do in normal usage.

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

Read more at Django Docs: https://docs.djangoproject.com/en/dev/ref/models/meta/#django.db.models.options.Options.get_field

Solution 2 - Python

The question is regarding models, but for people trying to do the same for forms (that's how I ended up in this thread), I think this approach is quite simple and clear:

  1. In a template:
    {{form.name.field.max_length}}

  2. In python code (e.g. in the view)
    form.name.field.max_length

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatView Question on Stackoverflow
Solution 1 - PythonBen JamesView Answer on Stackoverflow
Solution 2 - PythonGinés HidalgoView Answer on Stackoverflow