Search code examples
jquerypythondjangodatepickerdjango-grappelli

jQuery datepicker localization in django admin 1.7 + django-grappelli 2.6.1


I'm still quite new to Django, so after finishing the official tutorial I'm trying to learn more by steps and attempts to solve common problems.

I'm currently stuck with finding a (possibily correct) way to have localized datepickers in my app's admin page, which works with django-grappelli.

I was trying to directly modify grappelli files, but I feel this might definitely not be the correct approach.

My app is quite simple, not very distant from where you are left with after the official tutorial.

I've slightly modified the admin.py file, like this:

[...]

@admin.register(Question)
class QuestionAdmin(admin.ModelAdmin):
    #fields = ['pub_date', 'question_text']
    #date_hierarchy = 'pub_date'
    class Media:
        js = ("/media/mytime/js/ui.datepicker-it.js",)

    list_display = ['question_text', 'pub_date']
    fieldsets = [
        (None,                  {'fields': ['question_text']}),
        ('+ Date information',  {'fields': ['pub_date'], 'classes': ['grp-collapse grp-closed']}),
    ]
    inlines = [ChoiceInline]
    actions = ['prepend_letter']

[...]

By adding:

class Media:
    js = ("/media/mytime/js/ui.datepicker-it.js",)

and correctly putting the file in the media directory, now the file appears in the page source code when browsing to the Question modification page.

Too bad this seems not to be enough, as the datepickers are still appearing untranslated.

I've tried to even inject directly via console the line:

$.datepicker.setDefaults( $.datepicker.regional[ "it" ] );

but it looks like I'm still far from doing it right. Any tips?


Solution

  • I don't think the problem is Django-related, but mostly jQuery/Grappelli-related.
    As far as I remember Grappelli ships with its own jQuery (Django admin does the same), and uses a namespace to avoid conflicts, so calling $.datepicker or jQuery.whatever won't interact with Grappelli's jQuery.

    If your ui.datepicker-it.js looks like this:

    jQuery(function($){
      // do something on $.datepicker ...
    });
    

    Try changing it with:

    (function($){
      // do something on $.datepicker ...
    })(grp.jQuery);
    

    With grp.jQuery being the jQuery package Grappelli should be using, as in Grappelli code

    On a side note, it looks like you're trying to serve a .js file using MEDIA_URL and MEDIA_ROOT (given the "/media/" portion in your path), but I'm quite sure the preferred way to serve static files and assets in Django is by using STATIC_ROOT and STATIC_URL. Anyway, this is just about best-practices and should not prevent your code to work in any way, since you said the file is correctly loaded.