views:

646

answers:

4

I am performing a lot of JavaScript work in the browser and would like to have some of that backend functionality in the front-end. Specifically, it would be nice to have the functions get(), save(), all() and count() available to the client. Additionally, it would be great to have the field list of the model already available in the generated JavaScript object.

Whether the current user can read or write the records is a separate issue I will deal with using Django's authentication. For the time being, retrieval would be a start.

In short, is there code that would generate a JavaScript model from a Django model?

Thanks.

A: 

It sounds like you want to JSON encode your object data. See JSON.org for more on the data format.

Greg
JSON encode only provides the object data. It does not offer the reference model (or its name) and none of the functionality. :(
Dimitry Z
+1  A: 

You need a data serializer. You can do it with django built in serializers. It is documented on official django site. http://docs.djangoproject.com/en/dev/topics/serialization/#topics-serialization

+3  A: 

It sounds like you're looking for a complete JavaScript interface to the model and queryset APIs. I can't imagine that this would have ever been done or even be a simple task. Not only would you need to somehow generate JavaScript instances of models (much more than JSON serialisation provides, since you also want the methods) but you'd need to expose a web service that can handle every kind of DB-API call. I can't even begin to imagine where to start and the security issues may be too numerous to easily overcome.

The alternative (and much simpler) approach would be to use one of the various Django REST modules and JSON serialization. You could perform an AJAX GET request on a resource, which can be identified by a series of query parameters that would be equivalent to chained queryset filters. This would return the JSON representation of the model's values. You can then modify the JavaScript object and use an overloaded AJAX POST request to persist the changes back to the server. You wouldn't have access to the model's methods, so that functionality would have to be reimplemented but making any changes to a model should be straightforward enough - This is basically the JavaScript equivalent of using an HTML form to modify data.

Andrew Ingram
A: 

I've started a project that I think does exactly what you're looking for. You can find it at http://github.com/bumby/jslib. It currently only supports get(), but I'm hoping to extend this soon. Feel free to contribute patches :)

jslib is a Django application aiming to simplify AJAX integration with your Django projects.

Martin Stenberg