django-facebook is not JSON serializable
I've been developing a django web-app, and I have to allow users to log in
using Facebook. In order to get this done I tried using django-facebook. I
simply followed their installation instructions but every time I try to
log-in with facebook I get the following error:
TypeError at /facebook/connect/
<open_facebook.api.OpenFacebook object at 0x7fb9311648d0> is not JSON
serializable
I've tried searching for all of the django-facebook related issues on
StackOverflow, and even rummaged through the issues on their GitHub repo,
but I couldn't find anything similar to my problem. I've also tried
searching for generic "object is not JSON serializable" questions, but I'm
not really sure how I would be able to apply any of those solutions since
the error seems to be happening in the django-facebook code.
Here's the full traceback:
Environment:
Request Method: POST
Request URL: http://foodtrip.ph/facebook/connect/?facebook_login=1
Django Version: 1.5.4
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'pinax_theme_bootstrap',
'django_forms_bootstrap',
'autocomplete_light',
'django_facebook',
'foodtrips')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django_facebook.middleware.FacebookCanvasMiddleWare')
Traceback:
File
"/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py"
in get_response
115. response = callback(request,
*callback_args, **callback_kwargs)
File
"/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py"
in wrapped_view
77. return view_func(*args, **kwargs)
File
"/usr/local/lib/python2.7/dist-packages/django_facebook/decorators.py"
in wrapped_view
98. response = self.authenticate(self.fn, request,
*args, **kwargs)
File
"/usr/local/lib/python2.7/dist-packages/django_facebook/decorators.py"
in authenticate
178. fn, request, graph=graph, *args, **kwargs)
File
"/usr/local/lib/python2.7/dist-packages/django_facebook/decorators.py"
in execute_view
137. result = view_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django_facebook/views.py"
in connect
40. response = _connect(request, graph)
File "/usr/local/lib/python2.7/dist-packages/django_facebook/views.py"
in _connect
81. request, connect_facebook=connect_facebook)
File
"/usr/local/lib/python2.7/dist-packages/django_facebook/connect.py" in
connect_user
82. user = _login_user(request, converter, auth_user,
update=update)
File
"/usr/local/lib/python2.7/dist-packages/django_facebook/connect.py" in
_login_user
110. login(request, authenticated_user)
File
"/usr/local/lib/python2.7/dist-packages/django/contrib/auth/__init__.py"
in login
91. request.session.cycle_key()
File
"/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/base.py"
in cycle_key
271. self.create()
File
"/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/db.py"
in create
34. self.save(must_create=True)
File
"/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/db.py"
in save
51.
session_data=self.encode(self._get_session(no_load=must_create)),
File
"/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/base.py"
in encode
84. serialized = self.serializer().dumps(session_dict)
File "/usr/local/lib/python2.7/dist-packages/django/core/signing.py"
in dumps
100. return json.dumps(obj, separators=(',',
':')).encode('latin-1')
File "/usr/lib/python2.7/json/__init__.py" in dumps
238. **kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py" in encode
201. chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py" in iterencode
264. return _iterencode(o, 0)
File "/usr/lib/python2.7/json/encoder.py" in default
178. raise TypeError(repr(o) + " is not JSON serializable")
Exception Type: TypeError at /facebook/connect/
Exception Value: is not JSON serializable
The settings file:
# Django settings for foodtripph project.
import os
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__),
os.pardir))
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
try:
DB_PASS = os.environ["DB_PASS"]
except KeyError:
error_msg = 'Please set the "DB_PASS" environment variable'
raise ImproperlyConfigured(error_msg)
try:
FACEBOOK_APP_ID = os.environ["FACEBOOK_APP_ID"]
except KeyError:
error_msg = 'Please set the "FACEBOOK_APP_ID" environment variable'
raise ImproperlyConfigured(error_msg)
try:
FACEBOOK_APP_SECRET = os.environ["FACEBOOK_APP_SECRET"]
except KeyError:
error_msg = 'Please set the "FACEBOOK_APP_SECRET" environment
variable'
raise ImproperlyConfigured(error_msg)
try:
SECRET_KEY = os.environ["SECRET_KEY"]
except KeyError:
error_msg = 'Please set the "SECRET_KEY" environment variable'
raise ImproperlyConfigured(error_msg)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add
'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'dev', # Or path to database file
if using sqlite3.
# The following settings are not used with sqlite3:
'USER': 'ubuntu',
'PASSWORD': DB_PASS,
'HOST': 'localhost', # Empty for
localhost through domain sockets or '127.0.0.1' for localhost
through TCP.
'PORT': '', # Set to empty string for
default.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG
is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ['.foodtrip.ph', '.foodtrip.ph.', '.facebook.com',
'.facebook.com.']
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Asia/Manila'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold
user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, "site_media", "uploads")
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = "/media/"
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, "site_media", "static")
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = "/static/"
# Additional locations of static files
STATICFILES_DIRS = [
]
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# List of callables that know how to import templates from various
sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
TEMPLATE_CONTEXT_PROCESSORS = [
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
'django.core.context_processors.request',
'django.contrib.messages.context_processors.messages',
#external
# 'account.context_processors.account',
'pinax_theme_bootstrap.context_processors.theme',
'django_facebook.context_processors.facebook',
]
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django_facebook.middleware.FacebookCanvasMiddleWare',
# 'account.middleware.LocaleMiddleware',
# 'account.middleware.TimezoneMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'foodtripph.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'foodtripph.wsgi.application'
TEMPLATE_DIRS = [
os.path.join(PROJECT_ROOT, 'site_media', 'templates'),
]
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
#theme
'pinax_theme_bootstrap',
'django_forms_bootstrap',
#external
# 'account',
'autocomplete_light',
'django_facebook',
#project
'foodtrips',
)
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
AUTH_USER_MODEL = 'django_facebook.FacebookCustomUser'
AUTHENTICATION_BACKENDS = (
'django_facebook.auth_backends.FacebookBackend',
'django.contrib.auth.backends.ModelBackend',
)
urls.py
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin, auth
from django.views.generic import TemplateView
import autocomplete_light
autocomplete_light.autodiscover()
admin.autodiscover()
urlpatterns = patterns('',
#static pages
url(r'^$', TemplateView.as_view(template_name='homepage.html'),
name='home'),
# apps
url(r'^foodtrips', include('foodtrips.urls', namespace='foodtrips')),
#account
# url(r'^account/', include('account.urls')),
url(r'^facebook/', include('django_facebook.urls')),
url(r'^accounts/', include('django_facebook.auth_urls')),
# autocomplete
url(r'^autocomplete/', include('autocomplete_light.urls')),
# admin
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
I have absolutely no idea how to go about fixing this problem. Any help is
greatly appreciated (and needed)!
downgrade to django==1.5.2
ReplyDeleteit seems something changed at 1.5.3 regarding the sessions manager which now tries to serialize session objects using json and the OpenFacebook object is not compatible with the default json serializer.
i just added an issue at github https://github.com/tschellenbach/Django-facebook/issues/374
ReplyDeleteThanks for this blogpost, the problem has been fixed in the latest release of django facebook (5.2.7). Cheers, Thierry
ReplyDelete