Question

I have changed the way URLS are handled in my Django app.

Previously I was posting my model IDs as named variables in the URLs. But now, I am instead embedding my model IDs in the URL itself which looks more elegant to me. However, doing so is seemingly giving me a problem TypeError: <myObject: Object #4> is not JSON serializable

My Django Application used to be structured like this:

Old urls.py:

url(r'^doSomethingStep1/?$', views.doSomethingStep1View, name='doSomethingStep1'),
url(r'^doSomethingStep2/?$', views.doSomethingStep2View, name='doSomethingStep2'),

Old views.py doSomethingStep1() function:

@login_required
def doSomethingStep1View(request):
    myObjectObj = Prediction.objects.get(pk=int(request.GET["p"]))
    ...                
    return HttpResponseRedirect(reverse("doSomethingStep2"))

This used to work fine. But now I have changed it to the code shown below:

New urls.py:

url(r'^doSomethingStep1/(?P<myObjectID>\d+)/(?P<myObjectSlug>[a-z0-9\-_]+)/?$', views.doSomethingStep1View, name='doSomethingStep1'),
url(r'^doSomethingStep2/(?P<myObjectID>\d+)/(?P<myObjectSlug>[a-z0-9\-_]+)/?$', views.doSomethingStep2View, name='doSomethingStep2')

New views.py doSomethingStep1() function:

@login_required
def doSomethingStep1View(request, myObjectID, myObjectSlug=None):
    ...
    return HttpResponseRedirect(reverse(
            "doSomethingStep2", 
            kwargs={
                'myObjectID': myObjectObj.id, 
                'myObjectSlug': myObjectObj.slug,
            }
        )
    )

Running this view now (by visiting /doSomethingStep1/4/myobject-4-slug) yields the following error in the Browser:

TypeError at /doSomethingStep1/4/myobject-4-slug <MyObject: myObject 4 Slug> is not JSON serializable

It's really confounding. Why is this happening and how to fix it? I have printed out the value of reverse and there is no problem with it. I have no clue why and where it is trying to serialize MyObject4. As far as I know, it shouldn't be trying to serialize this object.

Was it helpful?

Solution

Are you using Django 1.6? The default session serializer was switched to JSON, which can cause problems if you put something in the session that is not serializable. You can switch back to the old pickle serializer using the SESSION_SERIALIZER setting. See the 1.6 release notes for details:

https://docs.djangoproject.com/en/dev/releases/1.6/#default-session-serialization-switched-to-json

You didn't include all of your view code, but I'm betting you are putting a MyObject instance in the user's session, which wouldn't get serialized and throw the error until the redirect happens.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top