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

I am writing a convenience code that calls django.core.urlresolvers.reverse() to create links. However, I cannot 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 am using Django 1.5 on Python 2.7.

+4
source share
2 answers

I would consider creating a module test_urls.py

 from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^foo/$', lambda request: None, name='foo')) 

then specify 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 urlconf in your test, you need to make sure that it has the urlpatterns attribute. In Django 1.4, the following works.

 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) 
+4
source

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

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

Now, I do not know how to exactly change this behavior, you can create several urls.py for testing and calling them, but it is hardly difficult to bind to the URL module names in your settings.py .

The documentation isn-t very useful, it says basically you don't need to install urlconf param . So I would listen to him and try a different way.

Good luck

+1
source

Source: https://habr.com/ru/post/1486856/


All Articles