Thursday, May 31, 2012

Re: Admin Inline empty extra - how to access parent form model ID?

I found a noce solution, it only needs this tiny patch already proposed on the tracker :
https://code.djangoproject.com/ticket/17856
There's no reason this patch could not be merged in the trunk, it's self-contained

With this, I can override get_inline_instances in my ModelAdmin :

    def get_inline_instances(self, request, obj):
        inline_instances = []
        for inline_class in self.inlines:
            if inline_class.model == get_model('coop_local', 'Exchange'):
                inline = inline_class(self.model, self.admin_site, obj=obj)
            else:
                inline = inline_class(self.model, self.admin_site)
            inline_instances.append(inline)
        return inline_instances

The inline gets the obj parameter , puts it in a local attribute and deletes it to not bother the Inline superclass

class ExchangeInline(admin.StackedInline):

    def __init__(self, *args, **kwargs):
        self.parent_object = kwargs['obj']
        del kwargs['obj']  # superclass will choke on this
        super(ExchangeInline, self).__init__(*args, **kwargs)

    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'location':
            kwargs['queryset'] = self.parent_object.locations()
        return super(ExchangeInline, self).formfield_for_dbfield(db_field, **kwargs)

An finally in formfield_for_dbfield I can use parent_object to correctly filter my queryset, and this filtering works in any line of the formset : those which are bound to existing objects and the blank (extra ) ones !



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/TjtIgy_eh5IJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment