2

I am collecting current instance of a modeladmin class from url in admin.py as shown below. But now if I try to create a new form, it throws error because the url does not contain any id. How do I work around it in a django way? How do I get current instance of a modeladmin class in an inline class instance?

Below is my code in the inline class that throws error.

def get_object(self, request, model):
    object_id = resolve(request.path).args[0]   #throws index error when 'add new form is clicked'
    try:
        object_id = int(object_id)
    except ValueError:
        return None
    return model.objects.get(pk=object_id)
1
  • I fixed this by adding a try and except block for IndexError. I still do not know how to access modeladmin instance from inline class instance. Commented Oct 22, 2015 at 21:27

1 Answer 1

3

When you register the AdminClass in the admin_site, Django instantiate the admin class to save in the registry ( a dict), where the key is the ModelClass, and the value is the ModelAdminClass instance,

From Inline Instance you can access to the parent_model, and then search in the registy

def get_object(self, request, model):
    ...
    admin_site._registry[self.parent_model]
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent way, or admin.site._registryin my case!
How to access attribute of parent model from inline? I am trying to check values using clean from inline formset or inline form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.