Django: maximum model length and maxlength form

I need to somehow bind the max_length model constraints to a Form object.

Say I am defining a model with a field: name = models.CharField(max_length=30)
Now I am defining a Form object with the same field:name = forms.CharField(max_length=30)

The question is, is there somewhere to sync the two? If I first define a model, can I define a max_lengthForm class based on what I did with the Model class?

+3
source share
2 answers

Using ModelForm makes sense if you have a form linked directly to the model.

Another way to get the max_length attribute from the model is to use the _metamodel attribute as follows:

>>> SomeModel._meta.get_field('some_field').max_length
64
>>>

So:

from models import *

class MyForm(forms.Form):
    some_field = forms.CharField(label='Some Field', 
            max_length=SomeModel._meta.get_field('some_field').max_length)

CharField docs

+6
source

All Articles