C. Gary C. Gary - 2 months ago 5
HTML Question

How to reference Django application url in admin index template

I'm currently making changes to the admin/index.html template and I need to reference the url in my application using the name space 'hello' in a href tag for a link, but I'm having trouble doing at the admin level. The name of my application is clean and the url pattern in urls.py file is below.

urls.py

from django.conf.urls import url, include
from . import views

urlpatterns = [
url(r'^HelloWorld/$', views.hello, name='hello'),
]


I'm trying to avoid hard coding the below href tag in admin/index.html. Any suggestions would be a great help


<div>
<h3>Hello World</h3>
<a href="http://127.0.0.1:8000/clean/HelloWorld">Test</a>
</div>




Answer

You can simply use:

<div>
    <h3>Hello World</h3>
    <a href="{% url 'hello' %}">Test</a>
</div>

Django provides the ability to "reverse" URLs (i.e. provided the name of the URL, and arguments if necessary, the actual URL is generated) in order to avoid such hardcoding.You can read more about URL reversing in the official docs here.

Comments