Search code examples
djangoeventsbackendinline-formset

Django Inlines and DateTimeField


I'm trying to create simple Event app, so I've decided to create event and some inline event occurances:

class EventOccurenceInline(admin.TabularInline):
    model = models.EventOccurance
    form = forms.EventOccuranceForm
    pass


class EventAdmin(TranslatableAdmin):
    list_display = [ "internal_name"]
    inlines = [
        EventOccurenceInline,
    ]
    pass

and here is forms.py:

class EventOccurenceForm(TranslatableModelForm):
    start_date = forms.DateTimeField()
    end_date = forms.DateTimeField()
    class Meta:
        model = models.EventOccurence

But, when I open my backend I see only simple inputs instead of DateTime pickers, and even labels for those fields say nothing:

Screenshot

Does anyone know how to use those widgets inside inlines? What am I doing wrong?

thanks in advance, Michael


Solution

  • It looks like the problem is that you're declaring the start_date and end_date fields in the EventOccurenceForm class without any arguments.

    Here is a quote from Django's "Creating forms from models" documentation in the Overriding the default field types or widgets section:

    If you explicitly instantiate a form field like this, Django assumes that you want to completely define its behavior; therefore, default attributes (such as max_length or required) are not drawn from the corresponding model. If you want to maintain the behavior specified in the model, you must set the relevant arguments explicitly when declaring the form field.

    Why are you declaring the start_date and end_date fields in the EventOccurenceForm class, anyway? Is it because you're trying to only have those two fields in the form? If that's the case, you should use the fields attribute of the inner Meta class instead.

    I'm assuming the EventOccurence model's start_date and end_date fields are DateFields and, thus, within Django admin, they will have the AdminDateWidget widget by default. If, for some reason, that isn't the case and you can't change the model, you could always use the widgets attribute of the EventOccurenceForm class's inner Meta class, like this:

    from django.contrib.admin.widgets import AdminDateWidget
    
    class EventOccurenceForm(TranslatableModelForm):
        class Meta:
            model = models.EventOccurence
            widgets = {
                'start_date': AdminDateWidget,
                'end_date': AdminDateWidget,
            }