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

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.


Asked by: Stuart296 | Posted: 24-09-2021






Answer 1

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'),
)

Answered by: Jack234 | Posted: 25-10-2021



Answer 2

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.

Answered by: Rafael808 | Posted: 25-10-2021



Similar questions

How do you create a weak reference to an object in Python?

How do you create a weak reference to an object in Python?


How can I reference columns by their names in python calling SQLite?

I have some code which I've been using to query MySQL, and I'm hoping to use it with SQLite. My real hope is that this will not involve making too many changes to the code. Unfortunately, the following code doesn't work with SQLite: cursor.execute(query) rows = cursor.fetchall() data = [] for row in rows data.append(row["column_name"]) This gives the following error: T...


python - How can I get the number of records that reference a particular foreign key in Django?

I'm working on a blog application in Django. Naturally, I have models set up such that there are Posts and Comments, and a particular Post may have many Comments; thus, Post is a ForeignKey in the Comments model. Given a Post object, is there an easy way (ideally, through a method call) to find out how many Comments belong to the Post?


c++ - How do I define a SWIG typemap for a reference to pointer?

I have a Publisher class written in C++ with the following two methods: PublishField(char* name, double* address); GetFieldReference(char* name, double*&amp; address); Python bindings for this class are being generated using SWIG. In my swig .i file I have the following: %pointer_class(double*, ptrDouble); This lets me publish a field that is defined in ...


reference counting - Python: pass c++ object to a script, then invoke extending c++ function from script

First of all, the problem is that program fails with double memory freeing ... The deal is: I have FooCPlusPlus *obj; and I pass it to my script. It works fine. Like this: PyObject *pArgs, *pValue; pArgs = Py_BuildValue("((O))", obj); pValue = PyObject_CallObject(pFunc, pArgs); where pFunc is a python function... So, my script has function, where ...


Why does Python keep a reference count on False and True?

I was looking at the source code to the hasattr built-in function and noticed a couple of lines that piqued my interest: Py_INCREF(Py_False); return Py_False; ... Py_INCREF(Py_True); return Py_True; Aren't Py_False and Py_True global values? Just out of sheer curiosity, why is Python keeping a reference count for these variables?


c# - In managed code, how do I achieve good locality of reference?

Since RAM seems to be the new disk, and since that statement also means that access to memory is now considered slow similarly to how disk access has always been, I do want to maximize locality of reference in memory for high performance applications. For example, in a sorted index, I want adjacent values to be close (unlike say, in a hashtable), ...


Reference to Part of List - Python

If I have a list in python, how can I create a reference to part of the list? For example: myList = ["*", "*", "*", "*", "*", "*", "*", "*", "*"] listPart = myList[0:7:3] #This makes a new list, which is not what I want myList[0] = "1" listPart[0] "1" Is this possible and if so how would I code it? Cheers, Joe


python - How to get a reference to a module inside the module itself?

How can I get a reference to a module from within that module? Also, how can I get a reference to the package containing that module?


Python reference problem

I'm experiencing a (for me) very weird problem in Python. I have a class called Menu: (snippet) class Menu: """Shows a menu with the defined items""" menu_items = {} characters = map(chr, range(97, 123)) def __init__(self, menu_items): self.init_menu(menu_items) def init_menu(self, menu_items): i = 0 for item in menu_items: self.menu_items[se...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top