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 be done?
I'm trying to do it in my __init__
, but it throws an error saying that "'RegistrationFormTOS' object has no attribute 'email'". Does anyone know how I can do this?
Thanks.
Here is my form code:
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
To add a label to a form field of a Django form, then you just use the label attribute and set it equal in single or double quotes to the text that you want the label to consist of. Below we add a label to the favorite_fruit form field of a Django form.
label is used to change the display name of the field. label accepts as input a string which is new name of field. The default label for a Field is generated from the field name by converting all underscores to spaces and upper-casing the first letter.
CharField is generally used for storing small strings like first name, last name, etc. To store larger text TextField is used. The default form widget for this field is TextInput. CharField has one extra required argument: CharField.max_length. The maximum length (in characters) of the field.
To create a dropdown in Python Django model form, we can create a char field with the choices argument set to a tuple of choices in a model class. Then we can set the model class as the model for the form. to add the color field to the MyModel model class.
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.
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."), }, }
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', )
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.
Try on Models.py
email = models.EmailField(verbose_name="E-Mail Address")
email_confirmation = models.EmailField(verbose_name="Please repeat")
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With