在Django管理员中将内联条件化 [英] Making inlines conditional in the Django admin
本文介绍了在Django管理员中将内联条件化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模型,希望工作人员能够编辑该事件的日期。像这样:
I have a model that I want staff to be able to edit up to the date for the event. Like this:
class ThingAdmin(admin.ModelAdmin):
model = Thing
if obj.date < today: #Something like that
inlines = [MyInline,]
问题是,我在此级别无权访问obj实例。我尝试覆盖get_formset(),但没有成功。
The problem is, I don't have access to the obj instance at this level. I've tried overriding get_formset(), but didn't get anywhere.
请告知?
推荐答案
感谢注释中1.4的更改。我在这里的实现也不是线程安全的,因此它确实应该被删除。
Thanks to the comments for a change in 1.4. My implementation here wasn't thread safe either, so it really should have been deleted.
因为 get_formsets
被传递了对象并调用 get_inline_instances
,我们可以修改这两个函数以对该对象起作用。
Since get_formsets
is passed the object and calls get_inline_instances
, we can modify both functions to act on the object.
这应该起作用:
class ThingAdmin(admin.ModelAdmin):
model = Thing
inlines = [inline]
other_set_of_inlines = [other_inline]
def get_inline_instances(self, request, obj=None):
# ^^^ this is new
inline_instances = []
if obj.date > datetime.date(2012, 1, 1):
inlines = self.inlines
else:
inlines = self.other_set_of_inlines
for inline_class in inlines:
inline = inline_class(self.model, self.admin_site)
if request:
if not (inline.has_add_permission(request) or
inline.has_change_permission(request) or
inline.has_delete_permission(request)):
continue
if not inline.has_add_permission(request):
inline.max_num = 0
inline_instances.append(inline)
return inline_instances
def get_formsets(self, request, obj=None):
for inline in self.get_inline_instances(request, obj):
# ^^^^^ this is new
yield inline.get_formset(request, obj)
这篇关于在Django管理员中将内联条件化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文