Saturday, October 31, 2015

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

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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/21215bea-1acb-4f95-b77e-9c00601be69c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment