根据 Django 管理中的父模型预填充内联
我有两个模型,Event
和 Series
,其中每个 Event 都属于一个 Series。大多数情况下,活动的 start_time
与其系列的 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)
我在管理应用程序中使用内联,以便我可以一次编辑系列的所有事件。
如果已经创建了一个系列,我想使用该系列的 default_time
预先填充每个内联事件的 start_time
。到目前为止,我已经为事件创建了一个模型管理表单,并使用 initial
选项预先填充固定时间的时间字段。
#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 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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您需要通过 ModelAdmin 关闭一个函数:
这里的系列将是
series
实例。然后在内联管理类中:
编辑:这种方法将使您能够将您的
series
对象传递到表单,您可以在其中使用它来设置字段的默认值。I think you need to close a function over a ModelAdmin:
Here series will be the
series
instance.Then in the inline admin class:
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.