2009-03-12 20 views
51

Mam formularz, który dziedziczy z 2 innych formularzy. W mojej formie chcę zmienić etykietę pola, które zostało zdefiniowane w jednej z form nadrzędnych. Czy ktoś wie, jak można to zrobić?Formularz Django - zestaw etykiet

Próbuję to zrobić w moim __init__, ale powoduje to błąd informujący, że obiekt "RegistrationFormTOS" nie ma atrybutu "e-mail" ". Czy ktoś wie, jak mogę to zrobić?

Dzięki.

Oto mój kod forma:

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 

Odpowiedz

104

Należy użyć:

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

Uwaga najpierw należy użyć super połączenie.

7

Wy pola dostępowe w postaci pośrednictwem dict „” wpisali:

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

to jest tak, że nie trzeba się martwić o pól formularza po zderzeniu nazw z metodami klasy formularza. (W przeciwnym razie nie możesz mieć pola o nazwie "clean" lub "is_valid") Definiowanie pól bezpośrednio w treści klasy to w większości tylko wygoda.

1

To nie działa na modelu dziedziczenia, ale można ustawić etykietę bezpośrednio w modelu

email = models.EmailField("E-Mail Address") 
email_confirmation = models.EmailField("Please repeat") 
4

Można ustawić label jako atrybut ostrości podczas definiowania formularza.

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

Problem z tą odpowiedzią jest to, że nie wyjaśnia, w jaki sposób zmienić 'etykietę pola, który został zdefiniowany w jednym formy rodzica "- najważniejsza jest forma rodzica. – jamesc

+0

To nie działa dla mnie ... '__init __() dostał nieoczekiwany argument słowa kluczowego 'label''' – User

+0

Didnt' działa w formularzu administratora! – Raptor

22

Oto przykład wzięty z 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

jak go używać w szablonie django – user2413621

+2

Działa to tylko dla ModelForm. Nie Form – Elwin

Powiązane problemy