ehsan shirzadi ehsan shirzadi - 4 months ago 45
Python Question

'str' object is not callable,how to deal?

When I run my Python Django app, I receive an error:

'str' object is not callable

I've tried the solutions here: TypeError: 'str' object is not callable (Python), but they don't work for me. I'm trying to run the Django book sample:

# Create your views here.
from django.http import HttpResponse
import datetime

def current_time(request):
now =
html = "<html><head></head><body>%s</body></html>" % str(now)
return HttpResponse(html)

def hello(request,name):
return HttpResponse("Hello django")

def what(request):
return HttpResponse("what's the problem django?")

from django.conf.urls import patterns, include, url
from hello_django.views import current_time,hello,what

urlpatterns = patterns('',

This is the URL I'm trying:

Stack Trace:

TypeError at /what/
'str' object is not callable
Request Method: GET
Request URL:
Django Version: 1.5.1
Exception Type: TypeError
Exception Value:
'str' object is not callable
Exception Location: C:\Python27\lib\site-packages\django\core\handlers\ in get_response, line 115
Python Executable: C:\Python27\python.exe
Python Version: 2.7.4
Python Path:
['D:\\Developer Center\\PyCharm\\helloDjango',
'D:\\Developer Center\\PyCharm\\helloDjango',
Server time: Tue, 7 Jan 2014 11:44:30 +0330
Traceback Switch to copy-and-paste view

C:\Python27\lib\site-packages\django\core\handlers\ in get_response
response = callback(request, *callback_args, **callback_kwargs) ...
▶ Local vars


You need to give the actual view to url():

urlpatterns = patterns('',
    url(r'^time/$', current_time),
    url(r'^what/$', what),
    url(r'^hello/([a-zA-Z0-9]+)', hello),

Note that I removed the quotes around what and the other view functions.

You can still use strings in the url() configurations, but then you need to use a <modulename>.<viewname> syntax or name the module in the first argument to patterns() (the string), and then you also don't need to import the functions:

urlpatterns = patterns('',
    url(r'^time/$', 'hello_django.views.current_time'),
    url(r'^what/$', 'hello_django.views.what'),
    url(r'^hello/([a-zA-Z0-9]+)', 'hello_django.views.hello'),


urlpatterns = patterns('hello_django.views',
    url(r'^time/$', 'current_time'),
    url(r'^what/$', 'what'),
    url(r'^hello/([a-zA-Z0-9]+)', 'hello'),

See the detailed URL dispatcher documentation.