django-bootstrap-datepicker-plus
django-bootstrap-datepicker-plus copied to clipboard
Setting 'locale' dynamically
Describe the problem My users can have different locales. Therefore I need to set the locale of each widget dynamically on form creation. I couldn't find a solution to this in the documentation. If possible I'd like to get some input on my approach.
Setup Information (please complete the following information):
- OS: Windows 10
- Browser chrome, firefox
- Python version 3.7
- Django version 2.1
- Bootstrap version 4
[x] I have followed the configuration instructions and checked out the common error troubleshooting page.
Approach
forms.py
from django import forms
from bootstrap_datepicker_plus import DatePickerInput
from example.models import ExampleModel
class ExampleForm(forms.ModelForm):
class Meta:
model = ExampleModel
fields = [
'date',
]
widgets = {
'date': DatePickerInput(),
}
def __init__(self, *args, request=None, **kwargs):
super().__init__(*args, **kwargs)
if request:
self.fields['date'].widget = DatePickerInput(options={'locale': request.LANGUAGE_CODE})
views.py
[...]
form = ExampleForm(request=request)
Does LANGUAGE_CODE match with available locales?
At least in my case it does...maybe only for now.
Any update on this issue? I am trying to localize all date and times in my Django application by setting USE_l10N to True in my configuration. The date and times are formatted according to the locale requested by the browser. So for example a Dutch user sees a date like '25 mei 2020' and an English user would see 'May 25, 2020'.
I can get the Bootstrap datepicker to show Dutch names for months and days if I add options={'locale': 'nl'} in my form. Is it possible to let Bootstrap datepicker use the language that was requested by the user? Is'nt this what localized_fields = '__all__' is supposed to achieve?
This is what my form looks like:
class DeliveryForm(forms.ModelForm):
class Meta:
model = Delivery
fields = ['delivered_at', 'supplier', 'quantity']
localized_fields = '__all__'
widgets = {
'delivered_at': DateTimePickerInput()
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', 'Save'))
self.helper.layout = Layout(
Row(
Div('delivered_at', 'supplier','quantity', css_class='col-3')
)
)
class DatePickerForm(forms.Form):
date = forms.DateField(widget=DatePickerInput())
def __init__(self,*args,**kwargs):
django_language=kwargs.pop('django_language')
super(DatePickerForm,self).__init__(*args,**kwargs)
self.fields['date']=forms.DateField(widget=DatePickerInput(options={'locale':django_language}))