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.
Changing django admin default formats could be done changing the django locale formats for every type you want. Put the following on your admin.py file (or settings.py) to change datetime default format at your django admin. It will change the ModelAdmin's datetime formats on that file (or whole site if in settings).
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)
widgets.py
inside your Django appfrom 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.
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.
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.
Try to write your own Widget and then override yours like this:
class CustomerAdmin(admin.ModelAdmin):
formfield_overrides = {
models.DateField: { 'widget': AdminDateWidget },
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With