Display empty_record on required selectDateWidget in Django

According to the Django Doc on SelectDateWidget ( https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#selectdatewidget ), empty_label will be displayed if DateField not required. I noticed that if DateField is required, the default value for the widget will be January , 1 and <current-year> . Is there a way to make DateField mandatory, but showing a widget with empty_label (e.g. -----) in the initial form?

+5
source share
3 answers

Unfortunately, an empty label in SelectDateWidget is only used if the field is not required, but you can simply change this by subclassing SelectDateWidget and overriding the create_select method:

 class MySelectDateWidget(SelectDateWidget): def create_select(self, *args, **kwargs): old_state = self.is_required self.is_required = False result = super(MySelectDateWidget, self).create_select(*args, **kwargs) self.is_required = old_state return result 

But in this case, you may have to redefine the check of your field as well, so it will cause the error that is required for this field, and not this choice is invalid when the choice remains at an empty value.

+8
source

Looking at the SelectDateWidget code, there is no good way to do this (django 2.1.4). My solution was to add empty options on the client side (using jquery):

 $(document).ready(function() { $('#select-widget-id select').each(function() { if(!$(this).children('[value=""], [selected]').length) { $(this).prepend('<option value="" selected="selected">---</option>'); } }); }); 
0
source

Although create_select was removed in recent versions of Django, I was able to use an approach very similar to @GwynBleidD's answer by subclassing SelectDateWidget and overriding get_context.

 class MySelectDateWidget(SelectDateWidget): def get_context(self, name, value, attrs): old_state = self.is_required self.is_required = False context = super(MySelectDateWidget, self).get_context(name, value, attrs) self.is_required = old_state return context 
0
source

All Articles