'Django / error : Object of type *** is not JSON serializable
I have seen this is a common mistake and there are a lot of entries in StackOverflow, but I can't connect the dots on this one.
in my views.py, this one works
def start(request):
whichScene = request.session.get('whichScene')
myScene=Scenes.objects.get(name=whichScene)
scene_list=myScene.next.all()
return render(request,'scenes3d/start.html',
{'scene_list':scene_list})
this one doesn't work :
def newPage (request, scene_slug):
sceneToRender = Scenes.objects.get(name=scene_slug)
return render(request,'scenes3d/new_scene.html',
{"myScene" :sceneToRender })
It gives an error :
Exception Value: Object of type Scenes is not JSON serializable
Scenes is imported with :
from .models import Scenes
models.py
class Scenes(models.Model):
name = models.SlugField('Scene name', max_length=60,unique=True)
description = models.TextField(blank=True)
fileGltf = models.FileField(null=TRUE, blank=False, upload_to="3dfiles/")
record_date = models.DateTimeField('Scene date')
manager = models.ForeignKey(
settings.AUTH_USER_MODEL,
blank=True,
null=True,
on_delete=models.SET_NULL)
prev = models.ForeignKey(
'self',
related_name='next',
blank=True,
null=True,
on_delete=models.SET_NULL)
def __str__(self):
return self.name
Solution 1:[1]
Because the queryset sceneToRender = Scenes.objects.get(name=scene_slug)
is not a single object (which would be JSON serializable) you need to access the values
of by using this instead:
sceneToRender = Scenes.objects.get(name=scene_slug).values()
Then you can render your view.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tyler2P |