apiljic
apiljic

Reputation: 523

Empty choice with SelectDateWidget in django 1.11

For the SelectDateWidget, Django documentation states the following:

If the DateField is not required, SelectDateWidget will have an empty choice at the top of the list (which is --- by default). You can change the text of this label with the empty_label attribute. empty_label can be a string, list, or tuple. When a string is used, all select boxes will each have an empty choice with this label. If empty_label is a list or tuple of 3 string elements, the select boxes will have their own custom label. The labels should be in this order ('year_label', 'month_label', 'day_label').

However, it is not clear to me how to set empty choice with the required date field? I assume this is not a rare situation: without the empty choices, but with default values preselected, one can easily skip the required date field and save it with the default values without noticing.

Does someone knows how to do this?

Upvotes: 4

Views: 491

Answers (2)

rurp
rurp

Reputation: 1446

I was able to do this 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

This answer is similar to GwynBleidD's from the thread here: Display empty_label on required selectDateWidget on Django, but updated to work with more recent versions of Django.

Upvotes: 1

Julian Go
Julian Go

Reputation: 4472

Unfortunately looking at the code of SelectDateWidget there is no nice way to do this(django 2.1.4). My solution was to add the empty choices 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>');
    }
  });
});

Upvotes: 1

Related Questions