7

How can I customize the default date picker in Django Admin?

I want to remove the "today" link and set the month value in the graphical picker to another month than the current one.

2 Answers 2

7

I was able to customize the default date widget in the Django admin. I followed two tutorials (from Simple is Better than Complex and Django Custom Widget)

  1. Write a custom widget in a file called widgets.py inside your Django app
from django.forms import DateInput


class CustomDatePickerInput(DateInput):
    template_name = "app_name/widgets/custom_datepicker.html"

    class Media:
        css = {
            "all": (
                "https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.min.css",
            )
        }
        js = (
            "https://code.jquery.com/jquery-3.4.1.min.js",
            "https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.min.js",
            "https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/i18n/datepicker.es-ES.min.js",
        )

Notice that the CSS and JS files that you may need should be added in the internal Media class as shown in the code above. In this case it is adding styles for the custom date picker.

  1. Define the template for your widget, for more date picker's options see here, put this file in app_name/templates/app_name/widgets/custom_datepicker.html or make sure that this template matches the value of template_name in your custom widget:
{% load i18n %}

{% include "django/forms/widgets/input.html" %}
{% get_current_language as LANGUAGE_CODE %}

<script>
  $(function () {
    const DATE_PICKER_OPTIONS = {
      'en-us': {
        format: 'yyyy-mm-dd',
        language: ''
      },
      'es': {
        format: 'dd/mm/yyyy',
        language: 'es-ES'
      }
    };
    let options = DATE_PICKER_OPTIONS['{{ LANGUAGE_CODE }}'];
    $("input[name='{{ widget.name }}']").datepicker({
      format: options.format,
      language: options.language
    });
  });
</script>

In your case, you should add the option date (example: date: new Date(2014, 1, 14)) since you are also asking how to pick another month.

  1. You need to indicate what widget to use in date field when registering your model in the Django admin (use formfield_overrides)
@admin.register(YourModel)
class YourModelAdmin(admin.ModelAdmin):
    formfield_overrides = {models.DateField: {"widget": CustomDatePickerInput}}

Once this is completed, you will have a custom widget for dates in the Django admin. Keep in mind that this is just a guide, you can go further by reviewing the two tutorials I indicated.

Note: the implementation of this widget is also supporting internationalization.

5

Try to write your own Widget and then override yours like this:

class CustomerAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.DateField: { 'widget': AdminDateWidget },
    }

Not the answer you're looking for? Browse other questions tagged or ask your own question.