开发者

Django: model maxlength and form maxlength

开发者 https://www.devze.com 2023-03-04 13:57 出处:网络
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)

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)

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消