【问题标题】:Is it possible set field size on Model?是否可以在模型上设置字段大小?
【发布时间】:2011-10-07 22:31:48
【问题描述】:

是否可以在 Model 上写一个字段大小?

这是我的 form.py 的一部分,我想在我的模型上做类似的事情: email = forms.EmailField(label = "Email",widget=forms.TextInput(attrs={'size':'60',)

我无法在 Form 上定义此属性,因为我使用类关系。如果我在父类上声明“电子邮件”并且我的子类将使用此字段,它将显示它(模型排除将不起作用,因为在父类上声明了“电子邮件”属性)

models.py

class UserProfile(models.Model):
   nome = models.CharField('Nome Completo',max_length=100 ) 
   endereco = models.CharField('Endereço',max_length=100)
   ...

forms.py

class **cadastrousuarioForm**(formulariocadastrocompleto):   
   nome = forms.CharField(label = 'Nome',widget=forms.TextInput(attrs={'size':'30','maxlength':'100'}))
   ...

class atualizacaoousuarioForm(**cadastrousuarioForm**):   

    class Meta (cadastrousuarioForm):
        model = UserProfile
        fields = ("endereco",)   
        exclude = ("nome")
        ...

【问题讨论】:

    标签: django django-models django-forms


    【解决方案1】:

    不,无法在模型上定义字段大小。当在父项上定义字段时,您使用 exclude 描述的问题实际上是 Django 中的一个未解决的错误。从某种意义上说,你的挫败感是有道理的,但不幸的是,你没有太多选择。

    您可能想尝试混合:

    class MyFieldMixIn(forms.ModelForm):
        my_field = forms.CharField(label = 'Nome',widget=forms.TextInput(attrs={'size':'30','maxlength':'100'}))
    
    class ParentForm(forms.ModelForm):
        # Common functionality, fields, etc. here
    
    class ReplacementParentForm(ParentForm, MyFieldMixIn):
        pass
    
    class ChildForm(ParentForm):
        # Child-specific stuff here
    

    然后,您使用替换而不是使用父表单,因此您只能在该表单上获得该字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-19
      • 1970-01-01
      • 2020-01-18
      • 2014-12-15
      • 2016-02-05
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      相关资源
      最近更新 更多