Search code examples
pythonajaxdjangodjango-viewsdjango-sessions

Why is this Django view erroring out before it displays a debug print statement?


I have, for the development server in a Django project, a Django view where a 500 is generated, apparently before the view can run an initial debug output. The output from the development server, per intended Ajax hit, is:

Internal Server Error: /ajax/say
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/jonathan/unixytalk/unixytalk/views.py", line 71, in ajax_say
    request.session, room = room)):
  File "/Library/Python/2.7/site-packages/django/db/models/manager.py", line 163, in filter
    return self.get_queryset().filter(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 590, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 608, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 1198, in add_q
    clause = self._add_q(where_part, used_aliases)
  File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 1234, in _add_q
    current_negated=current_negated)
  File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 1125, in build_filter
    clause.add(constraint, AND)
  File "/Library/Python/2.7/site-packages/django/utils/tree.py", line 104, in add
    data = self._prepare_data(data)
  File "/Library/Python/2.7/site-packages/django/db/models/sql/where.py", line 79, in _prepare_data
    value = obj.prepare(lookup_type, value)
  File "/Library/Python/2.7/site-packages/django/db/models/sql/where.py", line 352, in prepare
    return self.field.get_prep_lookup(lookup_type, value)
  File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 1079, in get_prep_lookup
    return super(IntegerField, self).get_prep_lookup(lookup_type, value)
  File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 369, in get_prep_lookup
    return self.get_prep_value(value)
  File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 1073, in get_prep_value
    return int(value)
TypeError: int() argument must be a string or a number, not 'SessionStore'
[18/Jun/2014 11:34:28] "POST /ajax/say HTTP/1.1" 500 111136

The urlpatterns has:

url(r'^ajax/say/?$', 'unixytalk.views.ajax_say'),

The source for the function itself is:

#@ajax_login_required
@csrf_exempt
def ajax_say(request):
    print 'Reached here!'
    if not request.session.get('identifier', None):
        session = Session()
        session.save()
        request.session['identifier'] = session.id
    #print repr(request)
    #conversation = request.POST['conversation']
    #if not request.user in conversation.users:
        #return
    try:
        print repr(get_post(request))
        text = get_post(request)['params']['text']
        print 'Door 1'
        print repr(text)
    except KeyError:
        print 'Door 2'
        return HttpResponse(json.dumps([]), mimetype='application/json')
    except TypeError:
        print 'Door 3'
        return HttpResponse(json.dumps([]), mimetype='application/json')
    if get_post(request)['params'].get('time', None) != None:
        room = Room.objects.filter(identifier =
          get_post(request)['params']['room'])[0]
        if len(IndividualContribution.objects.filter(session =
          request.session, room = room)):
            instance = IndividualContribution.objects.filter(session =
              request.session, room = room)[0]
        else:
            instance = IndividualContribution(room = room, session =
              request.session['identifier'])
        instance.text = text
        instance.timestamp = get_post(request)['params']['timestamp']
        instance.save()
    return HttpResponse(json.dumps([]), mimetype='application/json')

This function is a work in progress, and intended for further refinement.

The development server's console output shows one or two hits without a server error, before displaying the error output above. (The page that references /ajax/say is supposed to give a brain dump every second, and what happens is an initial bit out putout without the error, then a 500 every second after that.) The non-error output is:

Inner Sanctum ~/unixytalk $ python manage.py runserver
Validating models...

0 errors found
June 18, 2014 - 11:34:26
Django version 1.6.2, using settings 'unixytalk.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Reached here!
{u'params': {u'room': u'ee8696bab4df6a68e0f3', u'time': 1403109268206}}
Door 2
 Reached here!
{"monologues": {}, "sessions": []}
 {"monologues": {}, "sessions": []}
/Library/Python/2.7/site-packages/django/http/response.py:330: DeprecationWarning: Using mimetype keyword argument is deprecated, use content_type instead
  super(HttpResponse, self).__init__(*args, **kwargs)

[18/Jun/2014 11:34:28] "POST /ajax/listen HTTP/1.1" 200 34
[18/Jun/2014 11:34:28] "POST /ajax/listen HTTP/1.1" 200 34
{u'params': {u'text': u'aaaa', u'room': u'ee8696bab4df6a68e0f3', u'time': 1403109268212}}
Door 1
u'aaaa'
[18/Jun/2014 11:34:28] "POST /ajax/say HTTP/1.1" 200 2

I'm guessing I'm trying to create a session object with a string or something non-integer for the ID, or something like that, i.e. that the first run creates pollution that affects the second and subsequent goes. "Session" is not Django's session, but an empty (Django model) class that is used to create a unique integer key.

--UPDATE--

In response to dhana, the models defined for this project are:

from django.contrib.auth.models import User
from django.db import models

from unixytalk import settings

class Room(models.Model):
    identifier = models.CharField(max_length =
      settings.MAX_HASH_LENGTH, null = True, blank = True)

class Session(models.Model):
    pass

class IndividualContribution(models.Model):
    room = models.ForeignKey(Room)
    session = models.IntegerField()
    text = models.TextField()
    timestamp = models.FloatField()
    username = models.TextField()

Solution

  • I think your error is here

    instance = IndividualContribution.objects.filter(session =
                  request.session, room = room)[0]
    

    when you querying the data,It gives this error

    TypeError: int() argument must be a string or a number, not 'SessionStore'
    

    It is asking string or number but you providing SessionStore.

    If you provide IndividualContribution model details I will give the more details.