1đź‘Ť
It is because the data you get back from the server is JSON. This needs to be parsed before it is loaded into your DOM. You could do something like this:
Copying, then adding to your test.html…
{% extends "base.html" %}
{% block main-menu %}
<div id="result"></div>
<script type="text/javascript">
$(function() {
$.get("/subjects-list", function(data){
var $results = $("#result");
for (var i = 0; i < data.length; i++) {
$results.append(data[i]["fields"]["name"] + "<br/>");
}
}, "json");
});
</script>
{% endblock %}
With that said though, you may want to look into using a javascript templating library. There are a LOT of them out there. The general idea is that the library can handle turning the AJAX responses into HTML.
There are some stackoverflow question answering the question of which to use here:
Recommended JavaScript HTML template library for JQuery?
What is the preferred template library for jQuery?
In order to find more about this, you’ll want to search for “javascript templating”.
1đź‘Ť
Don’t serialize your models directly, it isn’t safe as users would see sensible internal fields.
You want to use a real API engine, like django-tastypie or django-piston. With this kind of engine, you’ll be able to select fields that you want to show, manage authorizations, output formats, etc…
For instance, with tastypie
:
class SubjectResource(ModelResource):
class Meta:
queryset = Subject.objects.all()
resource_name = 'subjects'
fields = ['name']
Will produce:
{
"objects": [
{"name": "Math 140"},
{"name": "English 102"},
{"name": "CS210"},
]
}
Of course, you can delete the objects
wrapper with the following instance method:
def alter_list_data_to_serialize(self, request, data):
data[self.Meta.resource_name] = data['objects']
del data['objects']
del data['meta']
return data
That’s the cleanest way to go.