program tip

장고 양식-레이블 설정

radiobox 2020. 11. 13. 08:00
반응형

장고 양식-레이블 설정


2 개의 다른 양식에서 상속 된 양식이 있습니다. 내 양식에서 상위 양식 중 하나에 정의 된 필드의 레이블을 변경하고 싶습니다. 누구든지 이것이 어떻게 할 수 있는지 알고 있습니까?

내에서 시도하고 __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

다음을 사용해야합니다.

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

먼저 슈퍼 호출을 사용해야합니다.


다음 은 기본 필드 재정의에서 가져온 예입니다 .

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."),
            },
        }

'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.


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', )

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")

참고URL : https://stackoverflow.com/questions/636905/django-form-set-label

반응형