Django response error 'unicode' object has no attribute '_meta' json - django

I'm using django 1.11 and i'm getting a tough time in storing a Json response.Here's my views.py code
views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .models import addinfomodels
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.core import serializers
import json
# Create your views here.
def addinfo(request):
batch_year = [2016, 2017, 2018]
dept = ['AERO', 'BME', 'CIVIL', 'CSE', 'ECE', 'EEE', 'E&I', 'MECH']
type = ['onecredit', 'core', 'professional', 'openelective']
return render(request, "cbcsportal/addinfo.html", {'type': type, 'batch': batch_year, 'dept': dept})
def rollvalue(request):
return request.POST.get('rollno')
# d ={}
def jsonvalue(request):
d = {"courses":[{"choices": [request.POST.get('choices00') ,request.POST.get('choices10')], "code": request.POST.get('code0'), "name": request.POST.get('name10')}]}
ds = serializers.serialize('json', d)
print ds
return JsonResponse(ds, content_type="application/json", safe=False)
def posttodb(request):
if request.method == "POST":
data = addinfomodels()
data.batch = request.POST.get('batch')
data.dept = request.POST.get('dept')
data.typeid = request.POST.get('typeid')
data.type = request.POST.get('type')
data.rollno = [rollvalue(request)]
data.renderJSON = jsonvalue(request)
data.starttime = request.POST.get('starttime0')
data.endtime = request.POST.get('endtime0')
data.save()
return redirect('addinfo')
please help me i'm getting this error
'unicode' object has no attribute '_meta'
this is the traceback
Traceback:
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\admin\Desktop\SREC_OBA\cbcsportal\views.py" in posttodb
34. data.renderJSON = jsonvalue(request)
File "C:\Users\admin\Desktop\SREC_OBA\cbcsportal\views.py" in jsonvalue
21. ds = serializers.serialize('json', d)
File "C:\Python27\lib\site-packages\django\core\serializers__init__.py" in serialize
129. s.serialize(queryset, **options)
File "C:\Python27\lib\site-packages\django\core\serializers\base.py" in serialize
84. concrete_model = obj._meta.concrete_model
Exception Type: AttributeError at /cbcs/posttodb
Exception Value: 'unicode' object has no attribute '_meta'

Here:
d = {....}
ds = serializers.serialize('json', d)
#print ds
return JsonResponse(ds, content_type="application/json", safe=False)
You are passing a dict to serialize(). Django serializer are for serializing django's orm querysets (this is documented, and you could gave found out by reading the traceback).
The proper way to serialize a python dict to json is quite simply to use json.dumps(yourdict). BUT : in your case this is useless anyway, since JsonResponse expects a python dict as first argument and will take care of the serialization. Also you don't need to set the content type, it's already the default for JsonResponse. IOW, all you need is:
d = {....}
return JsonResponse(d, safe=False)
As a side note: here:
def posttodb(request):
if request.method == "POST":
data = addinfomodels()
data.batch = request.POST.get('batch')
data.dept = request.POST.get('dept')
data.typeid = request.POST.get('typeid')
data.type = request.POST.get('type')
data.rollno = [rollvalue(request)]
data.renderJSON = jsonvalue(request)
data.starttime = request.POST.get('starttime0')
data.endtime = request.POST.get('endtime0')
data.save()
You're inserting data in your db that are unvalidated, unsanitized user inputs. DONT DO THAT !!! (unless you're happy to have your server hacked by the first script kiddie of course). Use Django forms (in this case ModelForm to take care of validation and sanitization.

Related

Unable to perform conditional redirect from a class based view Django

I am trying to redirect a user who has already registered to a different view. here is the code for the views.py
However when qs.exists() = true I get an error
'The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.'
I am a beginner have read the documentation but unable to find where i am going worng.
Thanks
from django.shortcuts import render, redirect
from django.views import View
from Lpage.forms import SubscriberEntryForm
from Lpage.models import Subscriber
class homeview(View):
def get(self,request):
msg = request.session.get('msg', False)
if(msg):
del(request.session['msg'])
return render(request,'Lpage/index.html')
def post(self, request):
form = SubscriberEntryForm(request.POST or None)
if form.is_valid():
obj = form.save(commit=False)
qs = Subscriber.objects.filter(email__iexact=obj.email)
if qs.exists():
return redirect('messageview')
else:
obj.save()
request.session['msg'] = "msg"
return redirect(request.path)
def messageview(request):
return render(request,'Lpage/messages.html',{})
Here is the error message
ValueError at /
The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.
Request Method: POST
Request URL: http://localhost:8000/
Django Version: 3.2.7
Exception Type: ValueError
Exception Value:
The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.
Exception Location: C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 309, in check_response
Python Executable: C:\Users\Ganesamurthi\anaconda3\python.exe
Python Version: 3.8.5
Python Path:
['D:\dreamdoors\dd',
'C:\Users\Ganesamurthi\anaconda3\python38.zip',
'C:\Users\Ganesamurthi\anaconda3\DLLs',
'C:\Users\Ganesamurthi\anaconda3\lib',
'C:\Users\Ganesamurthi\anaconda3',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\win32',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\win32\lib',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\Pythonwin']
Server time: Wed, 29 Sep 2021 05:23:43 +0000
Traceback Switch to copy-and-paste view
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\exception.py, line 47, in inner
response = get_response(request) …
▶ Local vars
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 188, in _get_response
self.check_response(response, callback) …
▶ Local vars
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 309, in check_response
raise ValueError( …
▶ Local vars
redirect expects you to pass a URL but you gave it messageview, which is a view class in fact.
So you need to give redirect to the URL of messageview.

Django rest framework ```TypeError: type object argument after ** must be a mapping, not int``` being thrown

I have a SMSMessages model that will contain all the sms sent.I'm trying access via the django-rest-framework ListCreateAPIView class, but I keep on hitting error when I try to do an OPTION request on the api via Insomnia, TypeError at /smsmessages/
type object argument after ** must be a mapping, not int.
I searched on SO and found similar errors but they were caused b/c of a filter() argument, which doesn't apply to this.
I'm using django 2.2.5, python 3.6.8, django-rest-framework 3.10.3 and a mysqlclient 1.4.4.
this is the model of SMSMessages
from django.db import models
from django.contrib.auth.models import AbstractUser
from rest_framework.authtoken.models import Token
class SMSMessages(models.Model):
sms_number_to = models.CharField(max_length=14)
sms_content = models.CharField(max_length=160)
sending_user = models.ForeignKey("SMSUser", on_delete=models.PROTECT, related_name="user_that_sent", limit_choices_to=1)
sent_date = models.DateTimeField(auto_now=True)
delivery_status = models.BooleanField(default=False)
class Meta:
verbose_name_plural = "SMSMessages"
def __str__(self):
return self.sending_user
and this is this the urls.py file:
from django.urls import path
from rest_framework.authtoken import views
from rest_framework.routers import DefaultRouter
from notification.apiviews import SMSendView, SMSMessagesView
app_name = "notification"
router = DefaultRouter()
urlpatterns = [
path("smsmessages/", SMSMessagesView.as_view(), name="sms_messages"),
]
so the way I access it is by sending an OPTION request to http://localhost:8000/smsmessages/.
This the SMSMessagesview class that is used for the api view:
from rest_framework import generics, status, viewsets, permissions
from rest_framework.response import Response
from rest_framework.views import APIView
from django.shortcuts import get_object_or_404, get_list_or_404
from django.contrib.auth import authenticate
from commons.models import SMSMessages
from commons.serializers import SMSMessagesSerializer
class SMSMessagesView(generics.ListCreateAPIView):
"""
This class is responsible for generating, and returning, the view for all created objects of the SMSMessages model.
It sub-classes the ListCreateAPIView class from the generics module.
"""
queryset = SMSMessages.objects.all()
if not queryset:
Response(data={"{0} not found".format(queryset)}, status=404, content_type="application/json")
serializer_class = SMSMessagesSerializer
and this is the error:
TypeError at /notification/smsmessages/
type object argument after ** must be a mapping, not int
Request Method: OPTIONS
Request URL: http://localhost:8055/notification/smsmessages/
Django Version: 2.2.5
Python Executable: /home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/bin/python
Python Version: 3.6.8
Python Path: ['/home/gadd/vscodeworkspace/sms.et/api.sms.et', '/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python36.zip', '/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6', '/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages']
Server time: Sat, 5 Oct 2019 16:19:59 +0000
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework_swagger',
'rest_framework.authtoken',
'commons',
'notification']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
505. response = self.handle_exception(exc)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
465. self.raise_uncaught_exception(exc)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/views.py" in raise_uncaught_exception
476. raise exc
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
502. response = handler(request, *args, **kwargs)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/views.py" in options
516. data = self.metadata_class().determine_metadata(request, self)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/metadata.py" in determine_metadata
68. actions = self.determine_actions(request, view)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/metadata.py" in determine_actions
94. actions[method] = self.get_serializer_info(serializer)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/metadata.py" in get_serializer_info
111. for field_name, field in serializer.fields.items()
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/django/utils/functional.py" in __get__
80. res = instance.__dict__[self.name] = self.func(instance)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/serializers.py" in fields
360. for key, value in self.get_fields().items():
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/serializers.py" in get_fields
1047. source, info, model, depth
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/serializers.py" in build_field
1182. return self.build_relational_field(field_name, relation_info)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/serializers.py" in build_relational_field
1257. field_kwargs = get_relation_kwargs(field_name, relation_info)
File "/home/gadd/vscodeworkspace/sms.et/api.sms.et/api_env/lib/python3.6/site-packages/rest_framework/utils/field_mapping.py" in get_relation_kwargs
255. limit_choices_to = models.Q(**limit_choices_to)
Exception Type: TypeError at /notification/smsmessages/
Exception Value: type object argument after ** must be a mapping, not int
This is the serializer class used:
from rest_framework import serializers
from rest_framework.authtoken.models import Token
from commons.models import SMSUser, SMSPrice, Type, SMSMessages
class SMSMessagesSerializer(serializers.ModelSerializer):
"""
A class for serializing the SMSMessages model's data. It sub-classes the
ModelSerializer class from serializer's module.
"""
class Meta:
model = SMSMessages
fields = '__all__'
This same error is raised when I try to add an SMSMessages object to the db via the admin interface. Can anybody help?
From the documentation for ForeignKey.limit_choices_to, it...
sets a limit to the available choices for this field when this field is rendered using a ModelForm or the admin (by default, all objects in the queryset are available to choose). Either a dictionary, a Q object, or a callable returning a dictionary or Q object can be used.
...but in the model, you set an integer limit_choices_to=1 which is none of these things.
Did you perhaps intend to use something like limit_choices_to={'id': 1} to limit choices to SMS users with that ID?
That's just because you use limit_choices_to with wrong data format which defined by Django.
Either a dictionary, a Q object, or a callable returning a dictionary or Q object can be used.
So this caused the error:
sending_user = models.ForeignKey("SMSUser", on_delete=models.PROTECT, related_name="user_that_sent", limit_choices_to=1 # HERE)
So you might need to be clear what you want to do here to config the right filter so that Django Admin will will filter data when you select sending_user for your model. Like if you want to allow to select is_superuser only for sending_user on admin page then you can go with this:
limit_choices_to={
'is_superuser': True,
}

PIL module ImportError on Apache2 Server

I am getting this traceback on my Apache2 server when trying to upload an image. I am using Python 3.5.2 and Pillow 5.0.0 and Django 2.1.1
I was able to upload images successfully when I am working on my localhost, but when I uploaded this code to the apache2 server, then it gives this traceback. Pillow is in the requiremnts.txt though. No where in the code do I explicitly try to import PIL, but it seems to be getting called.
I have tried installing Pillow and PIL. I have tried to uninstall PIL, uninstall Pillow, I have tried re-install both. Nothing seems to be working.
View.py
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.core import serializers
from manager.models import Manager, Inspection
from . import InspectorService
from . import InspectionService
import json
from .forms import InspectionImageForm
... more unrelevant code here ...
def upload_image(request):
if request.method == 'POST':
form = InspectionImageForm(request.POST, request.FILES)
inspection_id = request.POST.get('inspection_id')
if form.is_valid():
m = Inspection.objects.get(id = inspection_id)
m.image = form.cleaned_data['image']
m.save()
return JsonResponse({'error': False, 'message': 'Uploaded Successfully', 'location': m.image.name})
else:
return JsonResponse({'error': True, 'errors': form.errors})
else:
return JsonResponse({'error': True, 'errors': 'Post error'})
forms.py
from django import forms
class InspectionImageForm(forms.Form):
image = forms.ImageField()
inspection_id = forms.IntegerField()
Traceback
File "/opt/myenv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/opt/myenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "/opt/myenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/www/html/CMPUT401/computronix/manager/views.py" in upload_image
119. if form.is_valid():
File "/opt/myenv/lib/python3.5/site-packages/django/forms/forms.py" in is_valid
185. return self.is_bound and not self.errors
File "/opt/myenv/lib/python3.5/site-packages/django/forms/forms.py" in errors
180. self.full_clean()
File "/opt/myenv/lib/python3.5/site-packages/django/forms/forms.py" in full_clean
381. self._clean_fields()
File "/opt/myenv/lib/python3.5/site-packages/django/forms/forms.py" in _clean_fields
397. value = field.clean(value, initial)
File "/opt/myenv/lib/python3.5/site-packages/django/forms/fields.py" in clean
584. return super().clean(data)
File "/opt/myenv/lib/python3.5/site-packages/django/forms/fields.py" in clean
147. value = self.to_python(value)
File "/opt/myenv/lib/python3.5/site-packages/django/forms/fields.py" in to_python
613. from PIL import Image
Exception Type: ImportError at /manager/upload_image/
Exception Value: No module named 'PIL'

Exporting data from App Engine datastore as a Google Drive spreadsheet

I have an app engine application on which I mark my monthly expenses along with some comments or reason. I would like to export these data into a
Google Drive Spreadsheet. I use Django framework.
I had gone through the tutorials provided by Google here.
But they have implemented it using webapp2 and jinja. Moreover, the doc for Implementing Using Django seems way too obsolete since I do not use Django ORM.
Below is my code sample which I use to upload. I strongly apologize if what I paste below is rubbish. Please help.
from django.utils.datastructures import SortedDict
import os
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.appengine import OAuth2DecoratorFromClientSecrets
decorator = OAuth2DecoratorFromClientSecrets(os.path.join(os.path.dirname(__file__ ), 'clientSecrets.json'), 'https://www.googleapis.com/auth/drive')
drive_service = build('drive', 'v2')
class Exporter(object):
serializedObjects = []
mime_type = 'text/plain'
fileToExport = None
request = None
def __init__(self, serializedObjects, request):
self.serializedObjects = serializedObjects
self.request = request
def createCSV(self):
import csv
import StringIO
stdout = StringIO.StringIO()
writer = csv.writer(stdout)
for obj in self.serializedObjects:
for value in obj.values():
writer.writerow([value])
# I will get the csv produced from my datastore objects here.
# I would like to upload this into a Google Spreadsheet.
# The child class ExportToSpreadSheet tries to do this.
return stdout.getvalue()
class ExportToSpreadSheet(Exporter):
def __init__(self, *args, **kwargs):
super(ExportToSpreadSheet, self).__init__(*args, **kwargs)
self.mime_type = 'application/vnd.google-apps.spreadsheet'
def create(self):
import datetime
valueToDrive = self.createCSV()
media_body = MediaFileUpload(valueToDrive, mimetype=self.mime_type, resumable=True)
body = {
'title' : 'MyExpense_%s' % datetime.datetime.now().strftime('%d_%b_%Y_%H_%M_%S'),
'description' : '',
'mimeType' : self.mime_type
}
self.fileToExport = drive_service.files().insert(body=body, media_body=media_body, convert=True)
return self.fileToExport
#decorator.oauth_aware
def upload(self):
if decorator.has_credentials():
self.create()
self.fileToExport.execute(decorator.http())
return self.fileToExport
raise Exception('user does not have the credentials to upload to google drive.')
#decorator.oauth_aware only works on webapp.RequestHandler subclasses. Why I am saying it is because I got this error while I ran the code.
INFO 2013-09-19 11:28:04,550 discovery.py:190] URL being requested: https://www.googleapis.com/discovery/v1/apis/drive/v2/rest?userIp=%3A%3A1
ERROR 2013-09-19 11:28:05,670 main.py:13] Exception in request:
Traceback (most recent call last):
File "/home/dev5/divya/jk/MyApp/ItsMyTuition/SDK/google_appengine/lib/django-1.2/django/core/handlers/base.py", line 100, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/dev5/divya/jk/MyApp/ItsMyTuition/ItsMyTuition/src/tuition/json/ajaxHandler.py", line 27, in mainHandler
responseValues = funtionToCall(*args)
File "/home/dev5/divya/jk/MyApp/ItsMyTuition/ItsMyTuition/src/tuition/json/ajaxHandler.py", line 69, in export
uploadedFile = exporterInstance.upload()
File "/home/dev5/divya/jk/MyApp/ItsMyTuition/ItsMyTuition/src/oauth2client/appengine.py", line 770, in setup_oauth
self._create_flow(request_handler)
File "/home/dev5/divya/jk/MyApp/ItsMyTuition/ItsMyTuition/src/oauth2client/appengine.py", line 734, in _create_flow
redirect_uri = request_handler.request.relative_url(
AttributeError: 'ExportToSpreadSheet' object has no attribute 'request'
INFO 2013-09-19 11:28:05,777 module.py:593] default: "POST /ajaxCall/export HTTP/1.1" 200 964
Since I am using Django framework I cannot get a Request handler as they except.
How can I integrate or do it in my scenario? I would very much appreciate any code samples or relevant links I may have missed.
Moreover, the whole thing happens in an ajax call.
Thanks in advance.
Use mimeType=text/csv and during the upload, request a conversion from csv to Spreadsheets:
drive_service.files().insert(covert=True, body=body, media_body=media_body, convert=True)

django simplejson [] is not JSON serializable

in my view, why does this work:
results = []
results.append({'status':1})
results.append({'bookmarks':[]})
simplejson.dumps(results)
# produces: []
and this doesn't:
from myapp.models import Bookmark
results = []
results.append({'status':1})
results.append({'bookmarks':Bookmark.objects.all()})
# fails with exception saying: [] is not JSON serializable
completely stack trace follows
Traceback:
File "/Users/Ishaq/Projects/github/bookmarks/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/Ishaq/Projects/github/bookmarks/bookmarks/views.py" in index
9. return HttpResponse(simplejson.dumps(Bookmark.objects.all()), mimetype='application/json');
File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py" in dumps
231. return _default_encoder.encode(obj)
File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in encode
201. chunks = self.iterencode(o, _one_shot=True)
File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in iterencode
264. return _iterencode(o, 0)
File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in default
178. raise TypeError(repr(o) + " is not JSON serializable")
Exception Type: TypeError at /conferences/
Exception Value: [] is not JSON serializable
Instead of using simplejson for serialize django objects, use serialization provided by django.
With reference form the link, you can do:
from django.core import serializers
data = serializers.serialize("json", Bookmark.objects.all())
I was waiting for Burhan Khalid to turn his comment into an answer, but since he hasn't, I would.
using simplejson.dumps(list(Bookmark.objects.all())) made it work