Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display empty_label on required selectDateWidget on Django

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

like image 835
Vicky Leong Avatar asked Sep 03 '15 14:09

Vicky Leong


1 Answers

Unfortunately, empty label in SelectDateWidget is only used if field is not required, but you can simply change this by subclassing SelectDateWidget and overriding 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 that case you may have to override also validation of your field, so it will throw error that field is required, not that choice is invalid when select is left on blank value.

like image 137
GwynBleidD Avatar answered Sep 21 '22 22:09

GwynBleidD