开发者

Prepopulating inlines based on the parent model in the Django Admin

开发者 https://www.devze.com 2022-12-13 14:45 出处:网络
I have two models, Event and Series, where each Event be开发者_如何学编程longs to a Series. Most of the time, an Event\'s start_time is the same as its Series\' default_time.

I have two models, Event and Series, where each Event be开发者_如何学编程longs 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?


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

精彩评论

暂无评论...
验证码 换一张
取 消