drec4s
drec4s

Reputation: 8077

Access Django model name from admin url pattern

Given an url like:

http://127.0.0.1:8000/admin/foo/bar/

How can I access the bar variable from the request, using the request.resolver_match.kwargs ?

What kwarg does the admin give too bar?

Tried different keys like class, content_type, slug, model, but none of them work.

EDIT:

It seems the correct kwarg is model_name which is returning None, however. I managed to extract the model name using:

request.resolver_match.url_name.split('_')[1]

But wondering if there is a more direct way.

Upvotes: 0

Views: 561

Answers (1)

Mikey Lockwood
Mikey Lockwood

Reputation: 1261

That should be just the app label. If you're hitting that url, then you are in the ModelAdminclass. To access the app label (foo in the question example) from ModelAdmin you can do self.model._meta.app_label, so you shouldn't need to go through the request.

You can access the model (bar in question the example) in ModelAdmin with self.model.

The model name won't be directly in the request object unless you put it there. You can get it from the request.path.strip('/').split('/')[-1] or from request.resolver_match.url_name.split('_')[1]

Upvotes: 1

Related Questions