46π
β
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
π€Peter Hoffmann
11π
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)])
π€Garth Kidd
- [Django]-Can we append to a {% block %} rather than overwrite?
- [Django]-Implementing Single Sign On (SSO) using Django
- [Django]-Resource temporarily unavailable using uwsgi + nginx
6π
For Python3 and Django 2:
from django.urls import reverse
url = reverse('my_app:endpoint', kwargs={'arg1': arg_1})
π€juan Isaza
- [Django]-How do I pass template context information when using HttpResponseRedirect in Django?
- [Django]-"Fixed default value provided" after upgrading to Django 1.8
- [Django]-STATIC_ROOT vs STATIC_URL in Django
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
).
π€zgoda
- [Django]-Coverage.py warning: No data was collected. (no-data-collected)
- [Django]-Getting Site Matching Query Does Not Exist Error after creating django admin
- [Django]-How do I access the request object or any other variable in a form's clean() method?
Source:stackexchange.com