5

I need to somehow hook the Model's max_length constraints into a Form object.

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

Question is, is there someway to synchronize the two? If I define a Model first, could I define the max_length of the Form class based on what I did with the Model class?

rene
  • 41,474
  • 78
  • 114
  • 152
reedvoid
  • 1,203
  • 3
  • 18
  • 34

2 Answers2

9

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

Another way to pick up the max_length attribute from a model is to use the _meta attribute of the model like so:

>>> 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

dting
  • 38,604
  • 10
  • 95
  • 114
1

Use ModelForms: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelform This way the forms inherit directly from the models and you do not have to repeat yourself.

Uku Loskit
  • 40,868
  • 9
  • 92
  • 93