简体   繁体   中英

TypeError: 'str' object is not callable (Django/Python)

I am attempting to build a REST-type JSON API for my app, and while I'm testing it, I keep getting a cryptic error when I hit the URL of my page.

URLconf:

url(r'^calendar/(?P<id>\d+)/(?P<year>\d+)/(?P<month>\d+)/$', 'calendar_resource'),

views.py:

def json_view(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return HttpResponse(json.dumps(result), mimetype="text/json")
    return wrapper    

@json_view
def calendar_resource(request, id, month, year):
    if id != request.user.id:
        return HttpResponseForbidden()
    thisMonthEnd = datetime.datetime(year, month, calendar.mdays[month])
    thisMonthStart = datetime.datetime(year, month, 1)
    l = Lesson.objects.filter(student__teacher = request.user).filter(startDate__lte=thisMonthEnd).filter(endDate__gte=thisMonthSta‌​rt)
    lessonList = list(l)
    return lessonList

I'm converting the QuerySet result to a list so I can do more operations on it (ie insert records that wouldn't be returned in the query) before passing the list back as JSON for processing by fullCalendar.

ETA: This is the original question that led me to use this implementation.

Traceback:

Environment:
Request Method: GET
Request URL: http://localhost:5678/calendar/1/2012/5/

Django Version: 1.3.1
Python Version: 2.6.5
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.humanize',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'lessons',
 'registration']
Installed Middleware:
('django.middleware.csrf.CsrfViewMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)

Exception Type: TypeError at /calendar/1/2012/5/
Exception Value: 'str' object is not callable

In your URLConf, it should be 'views.calender_resource' instead of just 'calender_resource' .

Essentially,

urlpatterns = patterns('',

    url(r'^calendar/(?P<id>\d+)/(?P<year>\d+)/(?P<month>\d+)/$', 'APP_NAME.views.calendar_resource'),
)

Or:

urlpatterns = patterns('APP_NAME.views',

    url(r'^calendar/(?P<id>\d+)/(?P<year>\d+)/(?P<month>\d+)/$', 'calendar_resource'),
)

where APP_NAME is the name of the app this view belongs to.


For reference :

url(regex, view, kwargs=None, name=None, prefix='')

You can use the url() function, instead of a tuple, as an argument to patterns(). This is convenient if you want to specify a name without the optional extra arguments dictionary. For example:

urlpatterns = patterns('',
    url(r'^index/$', index_view, name="main-view"),
    ...
)

This function takes five arguments, most of which are optional:

url(regex, view, kwargs=None, name=None, prefix='')

Could you please provide full traceback?

Issues so far:

  1. You cannot json.dumps on list of model instances directly. If you want such dump, have a look at django.core.serializers

     from django.core.serializers.json import Serializer Serializer().serialize(Lesson.objects.filter(...)) 
  2. 'application/json' is standard mime-type for json instead of 'text/json'

Check the field lookup syntax . You need to be passing kwargs to filter() . This means using __lt type syntax instead of the standard python comparison operators.

l = Lesson.objects.filter(student__teacher=request.user).filter(startDate__lte= thisMonth).filter(endDate__gte=thisMonthStart)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM