Django bootstrap3_datetime widget in admin site doesn't pass form data

47 views
Skip to first unread message

Ilia

unread,
Nov 1, 2015, 9:04:28 AM11/1/15
to Django users
I'm trying to replace the standard AdminSplitDateTime widget in my admin site for better functionality (basically I want to display only 'available' dates in my calender which I couldn't find how to do with the default picker). I decided to use the bootstrap3_datetime widget.

After overriding my field to use the new widget, it doesn't seem to be transferred into the 'clean' method (isn't in self.cleaned_data) for validation.

models.py

publish_time = models.DateTimeField('Date to publish')

admin.py

class MyForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        bad_dates = []
        #populating bad_dates with application logic

    def clean(self):

        # This will always return None when using the new widget.
        # When working with the default widget, I have the correct value.
        publish_time = self.cleaned_data.get('publish_time', None)


    publish_time = forms.DateTimeField(widget=DateTimePicker(options=
            {"format": "DD-MM-YYYY HH:mm",
             "startDate": timezone.now().strftime('%Y-%m-%d'),
             "disabledDates": bad_dates,
             })

class MyModelAdmin(admin.ModelAdmin):
    form = MyForm

admin.site.register(MyModel, MyModelAdmin)

HTML-wise, the widget works well and the text field is populated with the correct date (and with the 'bad_dates' disabled). The problem is that it seems it isn't saved on the form.

I also tried initializing the widget in the init method by doing:

self.fields['publish_time'].widget = DateTimePicker(options=...)

But the result was the same.

I've analysed the POST request that is sent using each of the widgets. In the default admin widget, I see that it generates two fields: "publish_time_0" (for date) and "publish_time_1" (for time). In the bootstrap3 widget, only a single "publish_time" field is sent.

I'm assuming that the admin site understands that the field is a DateTimeField (from models), looks for id_0 and id_1 and that's why it fails. Does that make sense? Is there anyway around it?

Thanks a lot!
Ilia

Collin Anderson

unread,
Nov 5, 2015, 10:57:56 AM11/5/15
to Django users
Hi Ilia,

The default admin widget looks for id_0 and id_1, but if you use a custom widget, that is responsible for looking for its own value (like publish_time_1). You could check out DateTimePicker's source code to see what it's actually doing.

Thanks,
Collin
Reply all
Reply to author
Forward
0 new messages