Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a simple Django URLconf and reverse() on it for a test? (getting TypeError: unhashable type: 'list')

I am writing convenience code which calls django.core.urlresolvers.reverse() to generate links. However, I can't seem to write a simple URLconf for a quick test.

This is what I tried:

>>> from django.conf.urls import patterns, url
>>> conf = patterns('', url(r'^foo/$', lambda request: None, name='foo'))
>>> from django.core.urlresolvers import reverse
>>> reverse('foo', conf)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File ".../env/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 445, in reverse
    resolver = get_resolver(urlconf)
File ".../env/local/lib/python2.7/site-packages/django/utils/functional.py", line 27, in wrapper
    if mem_args in cache:
TypeError: unhashable type: 'list'

I'm using Django 1.5 on Python 2.7.

like image 224
Dan Passaro Avatar asked Jun 18 '13 15:06

Dan Passaro


2 Answers

I would consider creating a test_urls.py module

from django.conf.urls import patterns, include, url

urlpatterns = patterns('', url(r'^foo/$', lambda request: None, name='foo'))

then give the path to test_urls.py when you call reverse in your test.

reverse('foo', 'path.to.test_urls')

If you really want to create the urlconf in your test, you need to make sure it has a urlpatterns attribute. The following works in Django 1.4.

from django.conf.urls import patterns, url
from django.core.urlresolvers import reverse

class MockUrlConf(object):
    urlpatterns = patterns('', url(r'^foo/$', lambda request: None, name='foo'))

reverse('foo', MockUrlConf)
like image 166
Alasdair Avatar answered Oct 27 '22 02:10

Alasdair


reverse method's urlconf param is a string indicating the name of the module containing the urls. You may call it like this:

reverse('foo', 'your_app.urls' )

Now, I don't know how exactly change this behavior, you may create some urls.py for testing and calling them, but this seems hardly tight to the URL modules names in your settings.py.

The documentation isn-t very useful, it says basically you won't need to set urlconf param. So I would listen to it and try another way.

Good luck!

like image 32
Paulo Bu Avatar answered Oct 27 '22 01:10

Paulo Bu