Django: datepicker with locale

Purpose

I wanted to add a datepicker on DateFields to a Django project. Moreover, I wanted to update the datepickers depending on locale.

All the plugins I found/tried were not maintained anymore or are just not working. Also, I was not very excited about installing a backend plugin for a frontend thing.


Dependencies



models.py

class Profile(AbstractBaseUser):
    # ...
    date_of_birth = models.DateField(_('date of birth'),null=True, blank=True)

forms.py

from django import forms
from functools import partial
DateInput = partial(forms.DateInput, {'class': 'datepicker', 'readonly':'true'})

class ProfileChangeForm(ModelForm):
    date_of_birth = forms.DateField(label=_('date of birth'),widget=DateInput())
    class Meta:
        model = Profile
        fields = ('avatar', 'gender', 'first_name','last_name', 'date_of_birth', 'phone')
    # ...

base.html

{% load staticfiles %}
{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}

<!DOCTYPE html>
<html lang="{{ LANGUAGE_CODE }}">
  <head>
    <!-- ... -->
  </head>
  <body>
    <!-- ... -->
    <!-- jquery -->
    <!-- bootstrap -->
    <script src="{% static "path/lib/datepicker/js/bootstrap-datepicker.min.js" %}" type="text/javascript"></script>
    <script src="{% static "path/lib/datepicker/js/locales/bootstrap-datepicker."|add:LANGUAGE_CODE|add:".min.js" %}" type="text/javascript" charset="UTF-8"></script>
  </body>
</html>

index.js

$(document).ready(function() {
  language_code = $('html').attr('lang');
  $.fn.datepicker.defaults.language = language_code;
  // ...
});


Conclusion

I hope this could help. That's not a revolution but it took me more than 1 hour to realise that I'll have to implement it and then, to do it.

Disclaimer: I'm not a web developer, feel free to tell me if there is a better way or if I've made some mistakes ;)

By @Mathieu Thoretton in
Tags :

Comments !