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_l开发者_开发问答ength=30)
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?
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
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.
精彩评论