I’ve got a brand new Django project. I’ve added one minimal view function to views.py, and one URL pattern to urls.py, passing the view by function reference instead of a string:
# 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')
I’m trying to use reverse() 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:
>>> from django.core.urlresolvers import reverse >>> import urls >>> from myapp import views >>> urls.urlpatterns[0].callback is views.myview True >>> reverse(views.myview) Traceback (most recent call last): File '<console>', line 1, in <module> 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 '<function myview at 0x6fe6b0>' with arguments '()' and keyword arguments '{}' not found.
As far as I can tell from the documentation, function references should be fine in both the URL pattern and reverse().
I’m using the Django trunk, revision 9092.
Got it!! The problem is that some of the imports are of
myproject.myapp.views, and some are just ofmyapp.views. This is confusing the Python module system enough that it no longer detects the functions as the same object. This is because your mainsettings.pyprobably has a line like:To solve this, try using the full import in your shell session:
Here’s a log of the debugging session, for any interested future readers:
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.pythe root URLconf, or in themyappapplication? There needs to be a full path from the root to a view for it to be resolved. If that’smyproject/myapp/urls.py, then inmyproject/urls.pyyou’ll need code like this: