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
Ding source
share