Django:model maxlength和form maxlength [英] Django: model maxlength and form maxlength

查看:94
本文介绍了Django:model maxlength和form maxlength的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以某种方式将Model的max_length约束绑定到一个Form对象中。说我定义一个带有一个字段的模型: 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)

CharField docs


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)

CharField docs

这篇关于Django:model maxlength和form maxlength的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆