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.