I have a problem in customizing labels in a Django
form
This is the
form code in file contact_form.py:
from django import forms
class ContactForm(forms.Form):
def __init__(self, subject_label="Subject", message_label="Message", email_label="Your email", cc_myself_label="Cc myself", *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['subject'].label = subject_label
self.fields['message'].label = message_label
self.fields['email'].label = email_label
self.fields['cc_myself'].label = cc_myself_label
subject = forms.CharField(widget=forms.TextInput(attrs={'size':'60'}))
message = forms.CharField(widget=forms.Textarea(attrs={'rows':15, 'cols':80}))
email = forms.EmailField(widget=forms.TextInput(attrs={'size':'60'}))
cc_myself = forms.BooleanField(required=False)
The view I am using this in looks like:
def contact(request, product_id=None):
.
.
.
if request.method == 'POST':
form = contact_form.ContactForm(request.POST)
if
form.is_valid():
.
.
else:
form = contact_form.ContactForm(
subject_label = "Subject",
message_label = "Your Message",
email_label = "Your email",
cc_myself_label = "Cc myself")
The strings used for initializing the labels will eventually be strings dependent on the language, i.e. English, Dutch, French etc.
When I test the
form the email is not sent and instead of the redirect-page the
form returns with:
<QueryDict: {u'cc_myself': [u'on'], u'message': [u'message body'],
u'email':[u'
[email protected]'], u'subject': [u'test message']}>:
where the subject label was before. This is obviously a dictionary representing the
form fields and their contents.
When I change the file contact_form.py into:
from django import forms
class ContactForm(forms.Form):
"""
def __init__(self, subject_label="Subject", message_label="Message", email_label="Your email", cc_myself_label="Cc myself", *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['subject'].label = subject_label
self.fields['message'].label = message_label
self.fields['email'].label = email_label
self.fields['cc_myself'].label = cc_myself_label
"""
subject = forms.CharField(widget=forms.TextInput(attrs={'size':'60'}))
message = forms.CharField(widget=forms.Textarea(attrs={'rows':15, 'cols':80}))
email = forms.EmailField(widget=forms.TextInput(attrs={'size':'60'}))
cc_myself = forms.BooleanField(required=False)
i.e. disabling the initialization then everything works. The
form data is sent by email and the redirect page shows up. So obviously something the the init code isn't right. But what?
I would really appreciate some help.