How to generate urls in django

36,171

Solution 1

If you need to use something similar to the {% url %} template tag in your code, Django provides the django.core.urlresolvers.reverse(). The reverse function has the following signature:

reverse(viewname, urlconf=None, args=None, kwargs=None)

https://docs.djangoproject.com/en/dev/ref/urlresolvers/

At the time of this edit the import is django.urls import reverse

Solution 2

I'm using two different approaches in my models.py. The first is the permalink decorator:

from django.db.models import permalink

def get_absolute_url(self): 
    """Construct the absolute URL for this Item."""
    return ('project.app.views.view_name', [str(self.id)])
get_absolute_url = permalink(get_absolute_url)

You can also call reverse directly:

from django.core.urlresolvers import reverse

def get_absolute_url(self): 
    """Construct the absolute URL for this Item."""
    return reverse('project.app.views.view_name', None, [str(self.id)])

Solution 3

For Python3 and Django 2:

from django.urls import reverse

url = reverse('my_app:endpoint', kwargs={'arg1': arg_1})

Solution 4

Be aware that using reverse() requires that your urlconf module is 100% error free and can be processed - iow no ViewDoesNotExist errors or so, or you get the dreaded NoReverseMatch exception (errors in templates usually fail silently resulting in None).

Share:
36,171
Staale
Author by

Staale

Java and Python programmer dealing in web solutions.

Updated on June 20, 2021

Comments

  • Staale
    Staale almost 3 years

    In Django's template language, you can use {% url [viewname] [args] %} to generate a URL to a specific view with parameters. How can you programatically do the same in Python code?

    What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language.

  • Sam Stoelinga
    Sam Stoelinga over 13 years
    Is this the same as using the decorator? @models.permalink