1. b.93z.org
  2. Notes

2 obscure Django errors

'str' object is not callable

Traceback:
File "/home/user/projects/someproj/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  112.                         response = callback(request, *callback_args, **callback_kwargs)

Such strange exception is caused by string in URLconf (i.e. urls.py). Example:

from django.conf.urls import patterns, url


urlpatterns = patterns(
    '',
    url(
        r'^a/preview/$',
        'markdown_preview',  # <-- here it is
        name='markdown_preview'
    ),
)

This happened because view argument of django.conf.urls.url should be dotted path (if it is string) but it isn’t.

tuple indices must be integers, not str

Traceback (most recent call last):

  File "/home/user/projects/someproj/env/lib/python2.6/site-packages/django/core/servers/basehttp.py", line 280, in run
    self.result = application(self.environ, self.start_response)

  File "/home/user/projects/someproj/env/lib/python2.6/site-packages/django/core/servers/basehttp.py", line 674, in __call__
    return self.application(environ, start_response)

  File "/home/user/projects/someproj/env/lib/python2.6/site-packages/django/core/handlers/wsgi.py", line 245, in __call__
    response = middleware_method(request, response)

  File "/home/user/projects/someproj/env/lib/python2.6/site-packages/django/middleware/csrf.py", line 237, in process_response
    if response['Content-Type'].split(';')[0] in _HTML_TYPES:

TypeError: tuple indices must be integers, not str

This one is caused by comma. Seriously. Example:

@render_to('tmpl.html')
def view(request):
    return dict(a=1, b=2),  # <-- here it is

This happened because this particular implementation does not understand tuples:

from functools import wraps

from django.shortcuts import render_to_response
from django.template import RequestContext


def render_to(template_path):
    '''
    Decorator with the same functionality as render_to_response has,
    but uses decorator syntax.
    '''
    def decorator(func):

        @wraps(func)
        def wrapper(request, *args, **kwargs):
            output = func(request, *args, **kwargs)

            if not isinstance(output, dict):
                return output

            return render_to_response(
                template_path,
                output,
                context_instance=RequestContext(request)
            )

        return wrapper

    return decorator

Abuse of decorators always strikes back :) dict(a=1, b=2), is not dict, but tuple (note trailing comma), so isinstance check for dict fails.

© 2008–2017 93z.org