Django InlineModelAdmin:部分显示内联模型并链接到完整模型

时间:2010-01-22 21:53:15

标签: python django django-admin

我定义了几个模型:Journals,volumes,volume_scanInfo等。

日记可以有更多的卷,而卷可以有更多的scanInfo。

我想做的是:

  • 在期刊的管理页面中我想要内联(已完成)卷列表
  • 将上一个列表的每个卷连接到其管理页面,我可以在其中显示表单以编辑卷及其“扫描信息”内联列表。

所以我希望有类似的东西:

Journal #1 admin page
[name]
[publisher]
[url]
.....
list of volumes inline
    [volume 10] [..(other fields)..]   <a href="/link/to/volume/10">Full record</a>
    [volume 20] [..(other fields)..]   <a href="/link/to/volume/20">Full record</a>

然后

Volume #20 admin page
[volume number]
[..(other fields)...]
......
list of the scan info inline
    [scan info 33] [..(other fields)..]   <a href="/link/to/scaninfo/33">Full record</a>
    [scan info 44] [..(other fields)..]   <a href="/link/to/scaninfo/44">Full record</a>

我尝试做的是定义一个模型方法,该方法创建代码并尝试在管理中定义“volume inline”的类中使用它,但它不起作用。

换句话说

模型“Volume”的内容如下:

def selflink(self):
    return '<a href="/admin/journaldb/volume/%s/">Full record</a>' % self.vid
selflink.allow_tags = True

class VolumeInline(admin.TabularInline):
    fields = ['volumenumber', 'selflink']
    model = Volume
    extra = 1

但这会产生以下错误:

Exception Value: 'VolumeInline.fields' refers to field 'selflink' that is missing from the form.

有什么想法吗?

谢谢, 乔瓦尼

6 个答案:

答案 0 :(得分:29)

<强>更新 从Django 1.8开始,它就是内置的。

请参阅this answerthe official documentation

OLD ANSWER:

最后我找到了一个简单的解决方案。

我创建了一个名为linked.html的新模板,它是tabular.html的副本,我添加了此代码来创建链接。

{% if inline_admin_form.original.pk %}
          <td class="{{ field.field.name }}">
              <a href="/admin/{{ app_label }}/{{ inline_admin_formset.opts.admin_model_path }}/{{ inline_admin_form.original.pk }}/">Full record</a>
          </td>
{% endif %}

然后我创建了一个继承LinkedInline

的新模型InlineModelAdmin
#override of the InlineModelAdmin to support the link in the tabular inline
class LinkedInline(admin.options.InlineModelAdmin):
    template = "admin/linked.html"
    admin_model_path = None

    def __init__(self, *args):
        super(LinkedInline, self).__init__(*args)
        if self.admin_model_path is None:
            self.admin_model_path = self.model.__name__.lower()

然后,当我定义新的内联时,我只能使用我的LinkedInline而不是普通的InlineModelAdmin

我希望它对其他人有用。

乔瓦尼

答案 1 :(得分:25)

<强>更新

从Django 1.8开始,现在是built-in

回答Django&lt; = 1.7:

使用条件案例

将代码保存在 models.py
def selflink(self):
    if self.id:
        return "<a href='/link/to/volume/%s' target='_blank'>Edit</a>" % str(self.id)
    else:
        return "Not present"

selflink.allow_tags = True

admin.py 中,将自身链接添加为readonly字段:

class VolumeInline(admin.TabularInline):
    readonly_fields = ['selflink',]
    model = Volume

这对我有用。

答案 2 :(得分:13)

这是基于其他一些答案的可重复使用的mixin。这很方便,因为它适用于Tabular和Stacked inlines,并且不会破坏您的模型或管理代码。

# put this somewhere like admin_helpers.py
from django.core.urlresolvers import reverse

class InlineEditLinkMixin(object):
    readonly_fields = ['edit_details']
    edit_label = "Edit"
    def edit_details(self, obj):
        if obj.id:
            opts = self.model._meta
            return "<a href='%s' target='_blank'>%s</a>" % (reverse(
                'admin:%s_%s_change' % (opts.app_label, opts.object_name.lower()),
                args=[obj.id]
            ), self.edit_label)
        else:
            return "(save to edit details)"
    edit_details.allow_tags = True

# admin.py

class VolumeInline(InlineEditLinkMixin, admin.TabularInline):
    fields = ['foo', 'bar', 'edit_details']

class JournalAdmin(admin.ModelAdmin):
    inlines = [VolumeInline]

class ScanInfoInline(InlineEditLinkMixin, admin.StackedInline):
    fields = ['foo', 'bar', 'edit_details']

class JournalAdmin(admin.ModelAdmin):
    inlines = [ScanInfoInline]

答案 3 :(得分:9)

Django 1.8+ this is now much easier。只需将show_change_link = True添加到您的TabularInlineStackedInline子类中,如下所示:

class VolumeInline(admin.TabularInline):
    fields = ['volumenumber']
    model = Volume
    extra = 1
    show_change_link = True

如果模型有自己的注册ModelAdmin,Django会自动为每个内联项添加一个完整更改表单的链接。

答案 4 :(得分:3)

您是否尝试过Reversing admin URL系统? 这可能会给出类似的东西(在期刊页面中):

<ul>
{% for volume in original.volume_set.all %}
  <li>
    <a href="{% url admin:yourapp_volume_change volume.id %}">Edit {{ volume }}
    </a>
  </li>
{% endfor %}
</ul>

答案 5 :(得分:2)

经过一番摆弄后,我能够使用reverse()在InlineAdmin和TabularInline中完成这项工作。至少使用TabularInline,您要链接的字段必须列在'readonly_fields'中

# create a read-only inline with the first field linked
from django.core import urlresolvers
class YOUR_MODEL_Inline(LinkedTabularInline):
    max_num = 0 # remove the "Add another ..." link
    model = YOUR_MODEL_NAME
    fk_name = "YOUR_FOREIGN_KEY_NAME"
    fields = [ 'link_name', ] # , 'field1', 'field2', 'etc' ]
    readonly_fields = fields
    can_delete = False
    def link_name(self, obj):
        if obj.pk:
            url = urlresolvers.reverse('admin:%s_%s_change'
                % (obj._meta.app_label, obj._meta.module_name), args=[obj.id])
            # obj.MODEL_FIELD can be a text string or whatever you want
            return '<a href="{0}">{1}</a>'.format(url, obj.MODEL_FIELD) 
    link_name.allow_tags = True
    link_name.short_description = "MODEL_FIELD"

如果要链接到更改列表而不是更改视图,可以修改reverse()调用。 changelist不需要对象id。

    url = urlresolvers.reverse('admin:%s_%s_changelist' 
        % (obj._meta.app_label, obj._meta.module_name))
    return '<a href="{0}">{1}</a>'.format(url, obj.name)

如果要链接到对象的子集,可以向URL添加参数:

    return '<a href="{0}?YOUR_MODEL_FIELD__id__exact={1}">{2}</a>'.format(url, obj.id, obj.name)
相关问题