Django:model maxlength和form maxlength [英] Django: model maxlength and form maxlength
问题描述
name = models.CharField(max_length = 30)
现在我定义一个具有相同字段的Form对象:
name = forms.CharField(max_length = 30)
问题是,有没有同步两个?如果我先定义一个模型,我可以根据我使用Model类来定义Form类的
max_length
吗? 如果您有一个与模型直接相关的表单,则使用ModelForm是有意义的。
从模型中获取max_length属性的另一种方法是使用模型的 _meta
属性:
>>> SomeModel._meta.get_field('some_field')。max_length
64
>>>
so:
code>从模型导入*
类MyForm(forms.Form):
some_field = forms.CharField(label ='Some Field',
max_length = SomeModel。 _meta.get_field('some_field')。max_length)
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?
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)
这篇关于Django:model maxlength和form maxlength的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!