user3636189
user3636189

Reputation: 193

How to set name in SelectDateWidget on buttons for month, year and day?

In forms:

bir_date = DateField(widget=SelectDateWidget(years=range(1900, 2020), label="")

But until I not pressed on drop-down list for month, day or year, button looks like this (---).

How to make that not displayed (---) but displayed ('month', 'year', day)?

Upvotes: 0

Views: 259

Answers (1)

schillingt
schillingt

Reputation: 13731

Unfortunately you'll need to subclass SelectDateWidget. You'll see in the django source that none_value isn't made available to be changed in the init function.

Here's an untested example:

from django.forms.extras.widgets import SelectDateWidget

class CustomSelectDateWidget(SelectDateWidget):
    def get_none_value(self, field):
        return {
            "year": "Year",
            "month": "Month",
            "day": "Day",
        }[field]

    def create_select(self, name, field, value, val, choices):
        if 'id' in self.attrs:
            id_ = self.attrs['id']
        else:
            id_ = 'id_%s' % name
        if not (self.required and val):
            choices.insert(0, self.get_none_value(field))
        local_attrs = self.build_attrs(id=field % id_)
        s = Select(choices=choices)
        select_html = s.render(field % name, val, local_attrs)
        return select_html

If you wanted to make it even more flexible, you could override the init function to pass in a none_value dictionary and use that in get_none_value if it exists.

Upvotes: 1

Related Questions