I was able to configure the default date widget in the Django admin area. I followed two lessons (from Simple is Better than Complex and Django Custom Widget )
- Write your widget in a file called
widgets.py inside your Django application
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", )
Note that the CSS and JS files you may need to be added to the Media inner class as shown in the code above. In this case, it adds styles for custom date picker .
- Define a template for your widget, for more information on date selection options, see here , put this file in
app_name/templates/app_name/widgets/custom_datepicker.html or make sure that this template matches the template_name value 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 date option (example: date: new Date(2014, 1, 14) ), since you are also asking how to choose another month.
- You need to specify which widget to use in the date field when registering your model in the Django admin area (use
formfield_overrides )
@admin.register(YourModel) class YourModelAdmin(admin.ModelAdmin): formfield_overrides = {models.DateField: {"widget": CustomDatePickerInput}}
After that, you will have your own widget for dates in the Django admin area. Keep in mind that this is just a guide, you can go further by reading the two textbooks I have indicated.
Note: the implementation of this widget also supports internationalization.
source share