Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I successfully pass a function reference to Django’s reverse() function?
    text
    copied!<p>I’ve got a brand new Django project. I’ve added one minimal view function to <code>views.py</code>, and one URL pattern to <code>urls.py</code>, passing the view by function reference instead of a string:</p> <pre><code># urls.py # ------- # coding=utf-8 from django.conf.urls.defaults import * from myapp import views urlpatterns = patterns('', url(r'^myview/$', views.myview), ) # views.py ---------- # coding=utf-8 from django.http import HttpResponse def myview(request): return HttpResponse('MYVIEW LOL', content_type="text/plain") </code></pre> <p>I’m trying to use <code>reverse()</code> to get the URL, by passing it a function reference. But I’m not getting a match, despite confirming that the view function I’m passing to reverse is the exact same view function I put in the URL pattern:</p> <pre><code>&gt;&gt;&gt; from django.core.urlresolvers import reverse &gt;&gt;&gt; import urls &gt;&gt;&gt; from myapp import views &gt;&gt;&gt; urls.urlpatterns[0].callback is views.myview True &gt;&gt;&gt; reverse(views.myview) Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 254, in reverse *args, **kwargs))) File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 243, in reverse "arguments '%s' not found." % (lookup_view, args, kwargs)) NoReverseMatch: Reverse for '&lt;function myview at 0x6fe6b0&gt;' with arguments '()' and keyword arguments '{}' not found. </code></pre> <p>As far as I can tell from the documentation, function references should be fine in both the URL pattern and <code>reverse()</code>.</p> <ul> <li><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#passing-callable-objects-instead-of-strings" rel="noreferrer">URL patterns with function references</a></li> <li><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#reverse" rel="noreferrer"><code>reverse</code> with function references</a></li> </ul> <p>I’m using the Django trunk, revision 9092.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload