Prepopulating inlines based on the parent model in the Django Admin

前端 未结 1 505
遥遥无期
遥遥无期 2021-01-12 11:46

I have two models, Event and Series, where each Event belongs to a Series. Most of the time, an Event\'s start_time is the same as its

1条回答
  •  情话喂你
    2021-01-12 12:31

    I think you need to close a function over a ModelAdmin:

    def create_event_form(series):
        class EventForm(forms.ModelForm):
            def __init__(self, *args, **kwargs):
                # You can use the outer function's 'series' here
        return EventForm
    

    Here series will be the series instance. Then in the inline admin class:

    class EventInlineAdmin(admin.TabularInline):
        model = Event
        def get_formset(self, request, obj=None, **kwargs):
            if obj:
                self.form = create_foo_form(obj)
            return super(EventInlineAdmin, self).get_formset(request, obj, **kwargs)
    

    EDIT: This approach will enable you to pass your series object to the form where you can use it to set a default for your field.

    0 讨论(0)
提交回复
热议问题