Django Urlconfs name parameter

Asked

Viewed 439 times

2

In Urlconf below:

urlpatterns = [
    url(r'^$', views.index, name='index'),
]

What is the function of the parameter name? It is possible to explain with a practical example?

1 answer

4


The parameter name serves to reference the URL. For example, if you want to point a link to the index in the template, you would use the following code:

<a href="{% url 'index' %}">Acessar o index</a>

In the view, you can pick up the URL through the reverse. In this example a redirect is made:

from django.http import HttpResponseRedirect
from django.urls import reverse

def redirecionar_para_o_index(request):
    return HttpResponseRedirect(reverse('index'))

In the documentation you can see more details.

  • 1

    Thanks for the reply. Just add that the import "from Django.urls import Reverse" only works in Django 1.10. In Django 1.9, the correct import is "from Django.core.urlresolvers import Reverse".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.