Reputation: 1325
in my Django project I dynamically create the fields of ContactsForm class:
class ContactsForm(forms.Form):
def __init__(self, *args, **kwargs):
super(ContactsForm, self).__init__(*args, **kwargs)
self.fields['nome'].widget.attrs.update({
'class' : 'form-control',
'placeholder': 'your name *',
'type': 'text'
})
[..]
In the template:
[..]
#set language
<a href="/language/it">ITA</a> - <a href="/language/en">ENG</a>
{% if session_language == 'it' %}
[..]
{% else %}
[..]
{% endif %}
<form id="contactForm" name="sentMessage" method='POST' action=''>{% csrf_token %}
[..]
<div class="form-group" >
{{ form.nome }}
</div>
[..]
</form>
How can I pass the session_language
attribute to the ContactForm class so that I can use it as a flag to switch between the italian and english versions of the fields?
if lang == 'it':
self.fields['nome'].widget.attrs.update({
'class' : 'form-control',
'placeholder': 'il tuo nome *',
'type': 'text'
})
else:
self.fields['nome'].widget.attrs.update({
'class' : 'form-control',
'placeholder': 'your name *',
'type': 'text'
})
Thank you for any help you can provide.
EDIT:
as soon as I posted the question I realised that I can simply make the template use a different ContactForm based on the value of session_language
. In the views.py I can read the request.session['lang']
and instantiate a different form based on the lang value.
In views.py
if request.session[`lang`] == 'it':
form = ContactsForm()
else:
form = ContactsForm_eng()
Is there any more elegant way to do it?
Upvotes: 0
Views: 131
Reputation:
follow the access-the-request
you can try:
class ContactsForm(forms.Form):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(ContactsForm, self).__init__(*args, **kwargs)
self.lang = None
if self.request:
self.lang = self.request.session.get('lang')
in view.py
form = ContactsForm(request=self.request)
Upvotes: 2