在 django admin 中为内联项目添加完整更改表单的链接? [英] Adding links to full change forms for inline items in django admin?

查看:31
本文介绍了在 django admin 中为内联项目添加完整更改表单的链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于对象的标准管理更改表单,以及用于外键关系的常用 StackedInline 表单.我希望能够将每个内嵌项链接到其相应的全尺寸更改表单,因为内嵌项有自己的内嵌项,我无法嵌套它们.

I have a standard admin change form for an object, with the usual StackedInline forms for a ForeignKey relationship. I would like to be able to link each inline item to its corresponding full-sized change form, as the inline item has inlined items of its own, and I can't nest them.

我已经尝试了从自定义小部件到自定义模板的所有内容,但没有任何效果.到目前为止,我以片段形式看到的解决方案"似乎并不适用于内联.我正准备用 jQuery 尝试一些 DOM hacking,只是为了让它工作并继续前进.

I've tried everything from custom widgets to custom templates, and can't make anything work. So far, the "solutions" I've seen in the form of snippets just plain don't seem to work for inlines. I'm getting ready to try some DOM hacking with jQuery just to get it working and move on.

我希望我一定遗漏了一些非常简单的东西,因为这似乎是一项如此简单的任务!

I hope I must be missing something very simple, as this seems like such a simple task!

使用 Django 1.2.

Using Django 1.2.

推荐答案

我遇到了类似的问题,我想出了自定义小部件以及对模型形式的一些调整.这是小部件:

I had similar problem and I came up with custom widget plus some tweaks to model form. Here is the widget:

from django.utils.safestring import  mark_safe    

class ModelLinkWidget(forms.Widget):
    def __init__(self, obj, attrs=None):
        self.object = obj
        super(ModelLinkWidget, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        if self.object.pk:
            return mark_safe(
                u'<a target="_blank" href="../../../%s/%s/%s/">%s</a>' %
                      (
                       self.object._meta.app_label,
                       self.object._meta.object_name.lower(),
                       self.object.pk, self.object
                       )
            )
        else:
            return mark_safe(u'')

现在,由于每个内联小部件需要在构造函数中获取不同的对象,因此您不能仅以标准方式设置它,而是在 Form 的 init 方法中:

Now since widget for each inline need to get different object in constructor you can't just set it in standard way, but in Form's init method:

class TheForm(forms.ModelForm):
    ...
    # required=False is essential cause we don't
    # render input tag so there will be no value submitted.
    link = forms.CharField(label='link', required=False)

    def __init__(self, *args, **kwargs):
        super(TheForm, self).__init__(*args, **kwargs)
        # instance is always available, it just does or doesn't have pk.
        self.fields['link'].widget = ModelLinkWidget(self.instance)

这篇关于在 django admin 中为内联项目添加完整更改表单的链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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