Prepopulating inlines based on the parent model in the Django Admin

Posted by Alasdair on Stack Overflow See other posts from Stack Overflow or by Alasdair
Published on 2009-12-10T19:15:50Z Indexed on 2010/03/22 19:31 UTC
Read the original article Hit count: 534

Filed under:
|
|

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 Series' default_time.

Here's 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 the Events for a Series at once.

If a series has already been created, I want to prepopulate the start_time for each inline Event with the Series' default_time. So far, I have created a model admin form for Event, and used the initial option to prepopulate 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 start_time field is the Series' default_time?

© Stack Overflow or respective owner

Related posts about django

Related posts about django-forms