Reputation: 343
I need to get request parameters from views.py and use request.LANGUAGE_CODE to translate model object to the active language, since now I'm getting 'strings' object in default language, and not active. How should I proceed, in order to pass arguments from init function to a form widget?
From views.py:
form = ContactForm(lang=request.LANGUAGE_CODE)
forms.py:
from django import forms
from phonenumber_field.formfields import PhoneNumberField
from django.utils.translation import ugettext_lazy as _
from django.utils import translation
from .models import *
strings = Strings.objects.language().get(pk=1)
class ContactForm(forms.Form):
phone = PhoneNumberField(
min_length=9,
max_length=20,
widget=forms.TextInput(attrs={
'id': 'phone-number',
'placeholder': strings.placeholder,
})
)
def __init__(self, *args, **kwargs):
self.lang = kwargs.pop('lang', None)
super(ContactForm, self).__init__(*args, **kwargs)
Upvotes: 2
Views: 128
Reputation: 1702
Try this code:
def __init__(self, *args, **kwargs):
self.lang = kwargs.pop('lang', None)
super(ContactForm, self).__init__(*args, **kwargs)
form.fields['phone'].widget.attrs['placeholder'] = strings.placeholder[self.lang]
Of course, you should implement strings.placeholder[self.lang]
part (it is just an example) to localize your strings by language code.
Hope this helps.
Upvotes: 1