Reversing URL Patterns

... In Python


In [1]:
from django.core.urlresolvers import reverse

In [2]:
reverse('organizer_tag_list')


Out[2]:
'/tag/'

In [3]:
reverse(
    'organizer_tag_detail',
    args=['tag_slug_string'])


Out[3]:
'/tag/tag_slug_string/'

In [4]:
reverse(
    'organizer_tag_detail',
    kwargs={'slug': 'tag_slug_string'})


Out[4]:
'/tag/tag_slug_string/'

... in Templates


In [5]:
from django.template import Template, Context

In [6]:
code = "{% url 'organizer_tag_list' %}"
template = Template(code)
template.render(Context())


Out[6]:
'/tag/'

In [7]:
code = "{% url 'organizer_tag_detail' 'tag_slug_string' %}"
template = Template(code)
template.render(Context())


Out[7]:
'/tag/tag_slug_string/'

In [8]:
code = "{% url 'organizer_tag_detail' slug='tag_slug_string' %}"
template = Template(code)
template.render(Context())


Out[8]:
'/tag/tag_slug_string/'

The Case for get_absolute_url()


In [9]:
from django.core.urlresolvers import reverse
from organizer.models import Tag

In [10]:
django_tag = Tag.objects.get(slug__iexact='django')
reverse(
    'organizer_tag_detail',
    kwargs={'slug': django_tag.slug})


Out[10]:
'/tag/django/'

In [11]:
template_code = (
    "{% url 'organizer_tag_detail' tag.slug %}")
django_tag = Tag.objects.get(slug__iexact='django')
context = Context({'tag': django_tag})
template = Template(code)
template.render(context)


Out[11]:
'/tag/tag_slug_string/'

In [12]:
django_tag = Tag.objects.get(slug__iexact='django')
django_tag.get_absolute_url()


Out[12]:
'/tag/django/'

In [13]:
django_tag = Tag.objects.get(slug__iexact='django')
context = Context({'tag': django_tag})
code = "{{ tag.get_absolute_url }}"
template = Template(code)
template.render(context)


Out[13]:
'/tag/django/'

NoReverseMatch


In [14]:
from pprint import pprint
from django.core.urlresolvers import (
    NoReverseMatch, reverse)

In [15]:
try:
    reverse('no_url_pattern_with_this_name')
except NoReverseMatch as e:
    pprint(str(e), width=50)


("Reverse for 'no_url_pattern_with_this_name' "
 "with arguments '()' and keyword arguments "
 "'{}' not found. 0 pattern(s) tried: []")

In [16]:
# this needs a tag.slug values passed to args or kwargs!
try:
    reverse('organizer_tag_detail')
except NoReverseMatch as e:
    pprint(str(e), width=50)


("Reverse for 'organizer_tag_detail' with "
 "arguments '()' and keyword arguments '{}' "
 'not found. 1 pattern(s) tried: '
 "['tag/(?P<slug>[\\\\w\\\\-]+)/$']")