Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save meGAmeS1/76607896ee67d32dc9df to your computer and use it in GitHub Desktop.
Save meGAmeS1/76607896ee67d32dc9df to your computer and use it in GitHub Desktop.
Because I couldn't get the user locale working with django-bootstrap3-datetimepicker, I created this little workaround (that I put in the <head></head> of my main template).
{% get_current_language as LANGUAGE_CODE %}
<script type="text/javascript">
$(function () {
$.fn.datetimepicker.defaults.locale = moment.locale('{{ LANGUAGE_CODE }}');
});
</script>
@meGAmeS1
Copy link
Author

The script sets the moment.locale() to the locale the user selected in my django app and it overrides the default locale property of datetimepicker (stored in $.fn.datetimepicker.defaults). In my opinion, it isn't very pretty but it does the job.

@samuelcolvin
Copy link

Makes sense. TutorCruncher where we're using django-bootstrap3-datetimepicker has a completely different model for datetime formats decided in each companies setup, hence why we haven't had the problem.

Our base form class looks something like

class FormMixin(BSForm):
    def __init__(self, *args, **kwargs):
        super(FormMixin, self).__init__(*args, **kwargs)
        ...
        self.process_dt_format()

    def process_dt_format(self):
        for f in self.fields:
            if isinstance(self.fields[f], forms.DateField):
                self.fields[f].widget = DateTimePicker(
                    attrs={'data-format': self.dt_format['mt_date']},
                    options={'format': self.dt_format['mt_date'], 'minDate': '1900-01-01'}
                )
                self.fields[f].input_formats = self.dt_format['dj_date']
            elif isinstance(self.fields[f], forms.TimeField):
                self.fields[f].widget = DateTimePicker(
                    attrs={'data-format': self.dt_format['mt_time']},
                    options={'format': self.dt_format['mt_time']}
                )
                self.fields[f].input_formats = self.dt_format['dj_time']
            elif isinstance(self.fields[f], forms.DateTimeField):
                self.fields[f].widget = DateTimePicker(
                    attrs={'data-format': self.dt_format['mt_datetime']},
                    options={'format': self.dt_format['mt_datetime'], 'minDate': '1900-01-01', 'sideBySide': True}
                )
                self.fields[f].input_formats = self.dt_format['dj_datetime']

Where self.dt_format is a dict containing date, time and datetime formats for moment and other applications. You could probably do something similar using locale.

By the way, I doubt your snippet needs to go in head, is should come after moment and before datetimepicker are referenced after the rest of your HTML.

@samuelcolvin
Copy link

looking at this again perhaps moment_format should become an extra kwarg to the field which is transfered to both attrs: data-format and options: format

@meGAmeS1
Copy link
Author

My forms are very basics

class ExampleForm(forms.Form):
    date_to_pick = forms.DateField(
        widget=DateTimePicker(options={"format": "YYYY-MM-DD", "showClear": True}),
        required=True)

For the format of the date I want to set it like that YYYY-MM-DD regardless the language selected by the user. The reason I use locale is to get the widget with the right names for months and days (and also the right first day of week). Currently my app is available in English and French for the user, so depending on the language he chose he will get the widget like that:
Datetimepicker in French Datetimepicker in English

I tried to set the locale option through the declaration of the DateTimePicker widget :

  • By setting it statically it worked (with ̀'locale': 'fr'), but of course it wasn't what I was looking for
  • By setting it dynamically it failed (with django.utils.translation.get_language())

You're right about the fact I don't need to put my <script> block into the <head> but since I import all my *.js in the head (with the defer attribute) I just added this little block after the imports so almost all JS of my page is on the same part (except for the <script> block of the datetimepicker field).

Anyway, thank you again for your fork of the datetimepicker, it saved me a bunch a time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment