[Fixed]-How do I successfully pass a function reference to Django’s reverse() function?

11👍

Got it!! The problem is that some of the imports are of myproject.myapp.views, and some are just of myapp.views. This is confusing the Python module system enough that it no longer detects the functions as the same object. This is because your main settings.py probably has a line like:

ROOT_URLCONF = `myproject.urls`

To solve this, try using the full import in your shell session:

>>> from django.core.urlresolvers import reverse
>>> from myproject.myapp import views
>>> reverse(views.myview)
'/myview/'

Here’s a log of the debugging session, for any interested future readers:

>>> from django.core import urlresolvers
>>> from myapp import myview
>>> urlresolvers.get_resolver (None).reverse_dict
{None: ([(u'myview/', [])], 'myview/$'), <function myview at 0x845d17c>: ([(u'myview/', [])], 'myview/$')}
>>> v1 = urlresolvers.get_resolver (None).reverse_dict.items ()[1][0]
>>> reverse(v1)
'/myview/'
>>> v1 is myview
False
>>> v1.__module__
'testproject.myapp.views'
>>> myview.__module__
'myapp.views'

What happens if you change the URL match to be r'^myview/$'?


Have you tried it with the view name? Something like reverse ('myapp.myview')?

Is urls.py the root URLconf, or in the myapp application? There needs to be a full path from the root to a view for it to be resolved. If that’s myproject/myapp/urls.py, then in myproject/urls.py you’ll need code like this:

from django.conf.urls.defaults import patterns
urlpatterns = patterns ('',
    (r'^/', 'myapp.urls'),
)

1👍

If your two code pastes are complete, then it doesn’t look like the second, which makes the actual call to reverse(), ever imports the urls module and therefor if the url mapping is ever actually achieved.

Leave a comment