Django's serializer has some limitations which makes it a bit of a pain to use. Basically it will ignore any atributes that have been added to a model object.
The code below is for an alternative serializer. This version allows you select what attributes will be serialized on a per object basis. It also allows you to either serialize the data into json or xml.
The original json encoder was written by [Wolfram Kriesing](http://wolfram.kriesing.de/blog/)
Example Usage:
dumper = DataDumper()
dumper.selectObjectFields('class_name',[...fields...])
dumper.selectObjectFields('class_name',[...fields...])
dumper.dump(model_instance,'xml')
dumper.dump(model_instance,'json')
dumper.dump(queryset,'xml')
Another sample of how to integrate Django and jQuery.
===
This starts a function in views.py that takes a long time to finish. It sets a session variable so that another function can report on the situation. We use jquery and ajax to 'pull' that data from Django so as to provide a progress report.
I don't yet know how to background a long-running process, but this is an okay stop-gap method to use. I hope.
\d
Here is a Django template tag that allows you to create complex variables specified in JSON format within a template.
It enables you to do stuff like:
{% var as person %}
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
"212 555-1234",
"646 555-4567"
]
}
{% endvar %}
<p>{{person.firstName}}, </br>
{{person.address.postalCode}}, </br>
{{person.phoneNumbers.1}}
</p>
This tag also enables me to do dynamic CSS using as follows:
# urlpatters
urlpatterns = patterns('',
(r'^css/(?P<path>.*\.css)$', 'get_css'),
)
#views
def get_css(request, path):
return render_to_response('css/%s' % path, {},
mimetype="text/css; charset=utf-8")
# dynamic css within in /path/to/app/templates/css'
{% load var %}
{% var as col %}
{
"darkbg": "#999",
"lightbg": "#666"
}
{% endvar %}
{% var as dim %}
{
"thinmargin": "2em",
"thickmargin": "10em"
}
{% endvar %}
body {
background: {{col.darkbg}};
margin: {{dim.thinmargin}};
}
Another `JsonResponse` class, including comment wrapping. Extensions to other kinds of CSRF protection should be obvious. Good explanations of why such protections are needed would make excellent comments on this snippet.
This depends on the `json_encode` method in [snippet 800](http://www.djangosnippets.org/snippets/800/).
The Django JSON encoder already extends the `simplejson` encoder a little; this extends it more and gives an example of how to go about further extension.
Hopefully `newserializers` (see the community aggregator today) will supercede this, but until then, it's useful.
This is a subclass of Django's built-in JSONEncoder that adds the ability to output form and field objects as ExtJS-compatible config objects.
Simple example:
from django.utils import simplejson
json = {
'data': [],
'success': True,
'metaData': {
'fields': SFY09RDOForm(),
'root': 'data',
'successProperty': 'success'
},
}
return HttpResponse(simplejson.dumps(json, cls=ExtJSONEncoder))
Where SFY09RDOForm is a subclass of django.forms.Form.
6/20/2008: Updated to pass on the help_text parameter (useful in combination with this override in ext: http://extjs.com/forum/showthread.php?t=36642)
This function is designed to make it easier to specify client-side query filtering options using JSON. Django has a great set of query operators as part of its database API. However, there's no way I know of to specify them in a way that's serializable, which means they can't be created on the client side or stored.
`build_query_filter_from_spec()` is a function that solves this problem by describing query filters using a vaguely LISP-like syntax. Query filters consist of lists with the filter operator name first, and arguments following. Complicated query filters can be composed by nesting descriptions. Read the doc string for more information.
To use this function in an AJAX application, construct a filter description in JavaScript on the client, serialize it to JSON, and send it over the wire using POST. On the server side, do something like:
> `from django.utils import simplejson`
> `filterString = request.POST.get('filter', '[]')`
> `filterSpec = simplejson.loads(filterString)`
> `q = build_query_filter_from_spec(filterSpec)`
> `result = Thing.objects.filter(q)`
You could also use this technique to serialize/marshall a query and store it in a database.
Use this decorator on a function that returns a dict to get a JSON view, with error handling.
Features:
* response always includes a 'result' attribute ('ok' by default)
* catches all errors and mails the admins
* always returns JSON even on errors
**Explanation:**
I think this shortcut can be util for who uses JSON many times and does not want to write same code everytime.
**Setup:**
Saves the snippet as `myproject/utils.py` or add the code to some place in your project with same ends.
**Use in a view:**
from myproject.utils import render_to_json
from django.contrib.admin.models import User
def json_view(request):
admin_user = User.objects.get(username='admin')
return render_to_json(
'json/example.json',
locals(),
)
**Update:**
This code can be used as complement to [http://www.djangosnippets.org/snippets/154/](JsonResponse snippet) too.
This is a great way to pack extra data into a model object, where the structure is dynamic, and not relational. For instance, if you wanted to store a list of dictionaries. The data won't be classically searchable, but you can define pretty much any data construct you'd like, as long as it is JSON-serializable. It's especially useful in a JSON heavy application or one that deals with a lot of javascript.
**Example** (models.py):
from django.db import models
from jsonfield import JSONField
class Sequence(models.Model):
name = models.CharField(maxlength=25)
list = JSONField()
**Example** (shell):
fib = Sequence(name='Fibonacci')
fib.list = [0, 1, 1, 2, 3, 5, 8]
fib.save()
fib = Sequence.objects.get(name='Fibonacci')
fib.list.append(13)
print fib.list
[0, 1, 1, 2, 3, 5, 8, 13]
fib.get_list_json()
"[0, 1, 1, 2, 3, 5, 8, 13]"
*Note:* You can only save JSON-serializable data. Also, dates will be converted to string-timestamps, because I don't really know what better to do with them. Finally, I'm not sure how to interact with forms yet, so that realm is a bit murky.
An example of using Dojo to retrieve some information from a view (linked by the URL '/account/isavailable/') to show whether or not an account is available.
Simple template filter to encode a variable to JSON format
Usage:
{% load json_filters %}
{% block content %}
<script type="text/javascript"><![CDATA[
var items = {{ items|jsonify }};
]]></script>
{% endblock %}
I'm using JsonResponse for the views but I also want to have preloaded JSON data into the page output
I use this script to export a group of models that I want to import later as initial data. It exports them as serialized json, which is perfect for importing later with the loaddata function in manage.py.