Wednesday, 18 September 2013

render_template unable to jsonify object

render_template unable to jsonify object

I'm not doing a lot of web development, so my knowledge in this field is
pretty basic. However I have to write a simple web application using
python an flask.
In this application I have a simple class that looks like this:
class Task(object):
def __init__(self, id, title):
super(Task, self).__init__()
self.id = id
self.title = title
It can be assumed that id is an integer and title is a (unicode) string.
In a view function I want to render a template passing a list of Task
objects, like this:
@app.route('/tasklist')
@login_required
def tasklist():
tasklist = [
Task(1, u"Task 1"),
Task(2, u"Task 2"),
Task(3, u"Task 3"),
Task(4, u"Task 4")
]
return render_template( "tasklist.html", tasklist=tasklist)
When the view function is called, I get the following error message:
TypeError: <models.Task object at 0x103861210> is not JSON serializable
When I look around on the interwebs I see many examples, where they pass
lists of objects to views using render_template. So I wonder what am I
missing? My object only uses basic datatypes. Do I have to overload a
specific function?
Calling render_template with a list of simple strings (instead of class
instances) works fine.
I know, this is a very basic question, but I didn't find a satisfying
answer for now.

No comments:

Post a Comment