根据 Django Admin 中的父模型预填充内联 [英] Prepopulating inlines based on the parent model in the Django Admin

查看:24
本文介绍了根据 Django Admin 中的父模型预填充内联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,EventSeries,其中每个事件都属于一个系列.大多数情况下,事件的 start_time 与其系列的 default_time 相同.

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.

这是模型的精简版.

#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.

如果已经创建了一个系列,我想用系列的 default_time 为每个内联事件预填充 start_time.到目前为止,我已经为 Event 创建了一个模型管理表单,并使用 initial 选项用固定时间预填充时间字段.

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,]

我不知道如何从这里开始.是否可以扩展代码,以便 start_time 字段的初始值是系列的 default_time?

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?

推荐答案

我认为你需要通过 ModelAdmin 关闭一个函数:

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

这里的系列将是 series 实例.然后在内联管理类中:

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)

这种方法将使您能够将 series 对象传递给表单,您可以在其中使用它为您的字段设置默认值.

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.

这篇关于根据 Django Admin 中的父模型预填充内联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆