views:

69

answers:

1

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.

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!

Using Django 1.2.

+1  A: 

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

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'')

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__(*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)

I hope that helps.

Łukasz Korzybski
I haven't had time to try this, but it *looks* like it should work. :) Thanks.
David Eyk