'How do I reverse the URL of a Django admin template in a view?
I have a custom Django admin form registered, how do I programmatically find the URL for the template in a view?
I know my form is at /admin/custom_app/horse/ but how do I programmatically look that up, incase the from URL is changed in the future?
Here's how the form is registered:
admin.site.register(Horse, HorseAdmin)
Solution 1:[1]
First determine the url_name of the form. Use the relative address of where the form is, and find the name using resolve like so:
In [1]: from django.urls import resolve
...: match = resolve('/admin/custom_app/horse/')
...: match.url_name
...:
Out[1]: 'custom_app_horse_changelist'
Now you can use reverse to look up the URL, just remember to prefix admin: to it like so:
In [63]: from django.urls import reverse
...: reverse('admin:custom_app_horse_changelist')
Out[63]: '/admin/custom_app/horse/'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
