Reputation: 83517
As described this answer, we can use the url
tag to reverse Django admin URLs. However, in the examples shown there, you need the app name and model name in the string passed to url
. Is there a way to pass those in as parameters instead? What I'm looking to do is something like this:
{% url 'something here' app_name model_name object_id %}
What do I put for 'something here'
?
Upvotes: 5
Views: 8270
Reputation: 417
If you want to reverse admin urls, the default admin.sites.urls has a urlpattern in it that looks like:
urlpatterns = [
path('', wrap(self.index), name='index'),
path('login/', self.login, name='login'),
path('logout/', wrap(self.logout), name='logout'),
path('password_change/', wrap(self.password_change, cacheable=True), name='password_change'),
path(
'password_change/done/',
wrap(self.password_change_done, cacheable=True),
name='password_change_done',
),
path('jsi18n/', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'),
path(
'r/<int:content_type_id>/<path:object_id>/',
wrap(contenttype_views.shortcut),
name='view_on_site',
),
]
Looking at the above code you can simply use {% url 'admin:index' %}
in templete of reverse('admin:index')
else where for the admin dashboard url. Likewise same with all other admin urls patterns
Upvotes: 4
Reputation: 2579
I suggest using django_extensions
to use its show_urls
command to find url names.
simply do
pip install django_extensions
then add django_extensions
to your INSTALLED_APPS
#settings.py
INSTALLED_APPS = [
#...
'django_extensions',
]
Then you can run
python manage.py show_urls
You can use it with grep
to filter out the relevant URLs you need.
e.g.
python manage.py show_urls | grep password
/admin/auth/user/<id>/password/ django.contrib.auth.admin.user_change_password admin:auth_user_password_change
/admin/password_change/ django.contrib.admin.sites.password_change admin:password_change
/admin/password_change/done/ django.contrib.admin.sites.password_change_done admin:password_change_done
And say we want to use django.contrib.auth.admin.user_change_password
in our template:
We can do:
{% url "admin:auth_user_password_change" user.pk %}
P.S. You don't really need django_extensions
for your production environment, so you probably want to install it locally for development use only.
django_extensions installation documentation django_extensions commands
Upvotes: 23