Django form - set label

前端 未结 5 424
旧巷少年郎
旧巷少年郎 2020-12-12 19:19

I have a form that inherits from 2 other forms. In my form, I want to change the label of a field that was defined in one of the parent forms. Does anyone know how this can

相关标签:
5条回答
  • 2020-12-12 20:01

    It don't work for model inheritance, but you can set the label directly in the model

    email = models.EmailField("E-Mail Address")
    email_confirmation = models.EmailField("Please repeat")
    
    0 讨论(0)
  • 2020-12-12 20:03

    You can set label as an attribute of field when you define form.

    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', )
    
    0 讨论(0)
  • 2020-12-12 20:07

    You should use:

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

    Note first you should use the super call.

    0 讨论(0)
  • You access fields in a form via the 'fields' dict:

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

    That's so that you don't have to worry about form fields having name clashes with the form class methods. (Otherwise you couldn't have a field named 'clean' or 'is_valid') Defining the fields directly in the class body is mostly just a convenience.

    0 讨论(0)
  • 2020-12-12 20:12

    Here's an example taken from 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."),
                },
            }
    
    0 讨论(0)
提交回复
热议问题