reedvoid
reedvoid

Reputation: 1253

Django: model maxlength and form maxlength

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?

Upvotes: 7

Views: 12408

Answers (2)

dting
dting

Reputation: 39287

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

Upvotes: 10

Uku Loskit
Uku Loskit

Reputation: 42040

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.

Upvotes: 1

Related Questions