代码之家  ›  专栏  ›  技术社区  ›  TehOne

Django表单集标签

  •  85
  • TehOne  · 技术社区  · 17 年前

    我有一个继承自其他两个形式的形式。在我的表单中,我想更改在父表单之一中定义的字段的标签。有人知道如何做到这一点吗?

    我试着用我的 __init__ ,但它会抛出一个错误,指出“'RegistrationFormTOS'对象没有属性'email'”。有人知道我该怎么做吗?

    谢谢。

    from django import forms
    from django.utils.translation import ugettext_lazy as _
    from registration.forms import RegistrationFormUniqueEmail
    from registration.forms import RegistrationFormTermsOfService
    
    attrs_dict = { 'class': 'required' }
    
    class RegistrationFormTOS(RegistrationFormUniqueEmail, RegistrationFormTermsOfService):
        """
        Subclass of ``RegistrationForm`` which adds a required checkbox
        for agreeing to a site's Terms of Service.
    
        """
        email2 = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_(u'verify email address'))
    
        def __init__(self, *args, **kwargs):
            self.email.label = "New Email Label"
            super(RegistrationFormTOS, self).__init__(*args, **kwargs)
    
        def clean_email2(self):
            """
            Verifiy that the values entered into the two email fields
            match. 
            """
            if 'email' in self.cleaned_data and 'email2' in self.cleaned_data:
                if self.cleaned_data['email'] != self.cleaned_data['email2']:
                    raise forms.ValidationError(_(u'You must type the same email each time'))
            return self.cleaned_data
    
    8 回复  |  直到 17 年前
        1
  •  149
  •   Xbito    17 年前

    def __init__(self, *args, **kwargs):
        super(RegistrationFormTOS, self).__init__(*args, **kwargs)
        self.fields['email'].label = "New Email Label"
    

    请注意,首先您应该使用超级调用。

        2
  •  54
  •   Bakuriu    9 年前

    Overriding the default fields

    from django.utils.translation import ugettext_lazy as _
    
    class AuthorForm(ModelForm):
        class Meta:
            model = Author
            fields = ('name', 'title', 'birth_date')
            labels = {
                'name': _('Writer'),
            }
            help_texts = {
                'name': _('Some useful help text.'),
            }
            error_messages = {
                'name': {
                    'max_length': _("This writer's name is too long."),
                },
            }
    
        3
  •  18
  •   kiennt    12 年前

    您可以设置 label 作为定义表单时字段的属性。

    class GiftCardForm(forms.ModelForm):
        card_name = forms.CharField(max_length=100, label="Cardholder Name")
        card_number = forms.CharField(max_length=50, label="Card Number")
        card_code = forms.CharField(max_length=20, label="Security Code")
        card_expirate_time = forms.CharField(max_length=100, label="Expiration (MM/YYYY)")
    
        class Meta:
            model = models.GiftCard
            exclude = ('price', )
    
        4
  •  9
  •   Matthew Marshall    17 年前

    self.fields['email'].label = "New Email Label"
    

    这样您就不必担心表单字段和表单类方法的名称冲突。(否则,您不能有一个名为“clean”或“is_valid”的字段)直接在类体中定义字段主要是为了方便。

        5
  •  2
  •   Bender-51    15 年前

    email = models.EmailField(verbose_name="E-Mail Address")
    email_confirmation = models.EmailField(verbose_name="Please repeat")
    
        6
  •  1
  •   StupidWolf    5 年前

    email = models.EmailField("E-Mail Address")
    email_confirmation = models.EmailField("Please repeat")
    
        7
  •  0
  •   Suraj Rao Raas Masood    4 年前

    例如,以下操作将更改标签 s 新密码2 新密码确认 确认密码

    class MyPasswordChangeForm(PasswordChangeForm):
      PasswordChangeForm.base_fields['new_password2'].label = 'Confirm Password'
    

    进去看看 django/forms/forms.py ,你会看到的 .

    class Form(BaseForm, metaclass=DeclarativeFieldsMetaclass):
    ...
    
    class DeclarativeFieldsMetaclass(MediaDefiningClass):
        """Collect Fields declared on the base classes."""
        def __new__(mcs, name, bases, attrs):
            # Collect fields from current class and remove them from attrs.
            attrs['declared_fields'] = {
                key: attrs.pop(key) for key, value in list(attrs.items())
                if isinstance(value, Field)
            }
    
            new_class = super().__new__(mcs, name, bases, attrs)
    
            # Walk through the MRO.
            declared_fields = {}
            for base in reversed(new_class.__mro__):
                # Collect fields from base class.
                if hasattr(base, 'declared_fields'):
                    declared_fields.update(base.declared_fields)
    
                # Field shadowing.
                for attr, value in base.__dict__.items():
                    if value is None and attr in declared_fields:
                        declared_fields.pop(attr)
    
            new_class.base_fields = declared_fields
            new_class.declared_fields = declared_fields
    

    有一条评论

    class BaseForm:
    ...
        # The base_fields class attribute is the *class-wide* definition of
        # fields. Because a particular *instance* of the class might want to
        # alter self.fields, we create self.fields here by copying base_fields.
        # Instances should always modify self.fields; they should not modify
        # self.base_fields.