0

I'm tooling a widget for a datefield in my ModelForm wizard. I'd like to achieve this with a widget, so I can keep all the nice validation features of Django's ModelForm.

I am modeling my widget after this portion of django.forms.extras.widgets.SelectDateWidget:

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

Notice that I can add to the list of list choices by affecting the choices variable which changes the final html rendering via django.forms.widgets import Select

However, I would prefer to simply allow users to type in the year and date, instead of fumbling with dropdown menus. So for those, I have converted the widget to utilize this:

def create_input(self, name, field, value, val, none_value):
    if 'id' in self.attrs:
        id_ = self.attrs['id']
    else:
        id_ = 'id+%s' % name
    local_attrs = self.build_attrs(id=field % id_)
    inp = TextInput()
    select_html = inp.render(field % name, val, local_attrs)
    return select_html

It's working great, but it would be cool to set a default value here. Is this possible from the widget or the form?:

class EventRegistrationForm4(forms.ModelForm):
    class Meta:
        model = Event
        fields = ['start_date', 'start_time', 'end_time']
        this_year = datetime.date.today().year
        widgets = {
            'start_date': InputDateWidget(),
            }

1 Answer 1

1

I think you can do it simply in the widget, just test, if val is empty and if it is, then put in your default value like this:

def create_input(self, name, field, value, val, none_value):
    if 'id' in self.attrs:
        id_ = self.attrs['id']
    else:
        id_ = 'id+%s' % name
    local_attrs = self.build_attrs(id=field % id_)
    inp = TextInput()
    if val == None or val == '': 
        val = '2015-11-29' # or use datetime.now(), or compute another good default
    select_html = inp.render(field % name, val, local_attrs)
    return select_html
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.