Prepopulating inlines based on the parent model in Django Admin

I have two models: Eventand Series, where each event belongs to a series. In most cases, the event start_timecoincides with its series default_time.

Here is a stripped down version of the models.

#models.py

class Series(models.Model):
    name = models.CharField(max_length=50)
    default_time = models.TimeField()

class Event(models.Model):
    name = models.CharField(max_length=50)
    date = models.DateField()
    start_time = models.TimeField()
    series = models.ForeignKey(Series)

I use inlines in the admin application so that I can edit all events for the series at once.

If the series has already been created, I want to pre-populate a start_timeseries for each inline event default_time. So far I have created an administrator model for the event and used the parameter initialto pre-populate the time field with a fixed time.

#admin.py
...
import datetime

class OEventInlineAdminForm(forms.ModelForm):
    start_time = forms.TimeField(initial=datetime.time(18,30,00))
    class Meta:
        model = OEvent

class EventInline(admin.TabularInline):
    form = EventInlineAdminForm
    model = Event

class SeriesAdmin(admin.ModelAdmin):
    inlines = [EventInline,]

I am not sure how to proceed from here. Is it possible to extend the code so that the initial value for the field start_timeis the series' default_time?

+5
1

, ModelAdmin:

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

series. admin:

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: series , .

0

All Articles