Perhaps this is blindingly obvious but I spent a while trying to get this, before figuring out that when a each item of an iterated ValuesQuerySet is a dict.
Useful for serialising to JSON or XML etc.
Python json module or simplejson don't support Decimals out of the box. Here's an encoder that casts Decimals into floats and then displays them in desired format.
These base form classes add a method to return error messages as HTML encoded as JSON from Django, optionally passing in an argument to strip tags out. The method can be called in your view after checking that your form is valid. There is a ModelForm and Form class to use depending on your needs.
The sample jQuery function will take the errors returned as json, loop over the errors and insert the error after each field. If you're using a form prefix, you'll need to add a hidden field to hold the value for the prefix.
The `__all__` error(s), which are not bound to a field are appended to the end of the form, which you could easily reposition.
Happy coding!
If you're used to auto_render like I am (and think it's an awesome way to DRY code) and you want to support users with and without javascript enabled, this class is perfect.
You will need to provide the format requested, either through adding "(\.format)?" at the end of the url or through some middleware, but once you've done so this class will take care of rendering through the given template for normal users, JSON or JSONP for AJAX users.
From [fahhem.com](http://fahhem.com/) and [Recrec Labs](http://recreclabs.com/)
This fields.py file defines a new model field type, "JsonObjectField," which is designed to allow the storage of arbitrary Python objects in Django TextFields. It is intended primarily to allow the storage of Python dictionaries or list objects. As the name implies, it converts objects to JSON for storage; this conversion happens transparently, so from your model's perspective, the field stores and retrieves the actual objects.
Shows difference between two json like python objects. May help to test json response, piston API powered sites...
Shows properties, values from first object that are not in the second.
Example:
import simplejson # or other json serializer
first = simplejson.loads('{"first_name": "Poligraph", "last_name": "Sharikov",}')
second = simplejson.loads('{"first_name": "Poligraphovich", "pet_name": "Sharik"}')
df = Diff(first, second)
df.difference is ["path: last_name"]
Diff(first, second, vice_versa=True) gives you difference from both objects in the one result.
df.difference is ["path: last_name", "path: pet_name"]
Diff(first, second, with_values=True) gives you difference of the values strings.
Just like it says -- set it up and run. Use it for server migrations, for project handoffs, in cron jobs, you name it.
I have never had problems exporting models to individual fixtures in this way, and only one bout of trouble re-importing them (and that was, like, an impossible-triangle of OneToOneField dependencies anyway, and they were going from a sqlite file to a postgres schema that totally had inappropriate nullable columns in it). I find that the json files named for what they contain is helpful when and if manage.py does freak out during an import, as the output from `loaddata` command is so opaque it's autistic, basically.
A trivial refactoring effort could make it into a management command -- it already makes use of the builtin `dumpdata` command class internally. However I did not feel like overthinking it enough to set it up in a repository (doubtlessly padded with unrelated 'utilities' and explanatory .rst files) and then writing a blog post to sell it to you. That is why you are reading this code here, instead of on GitHub.
Don't get me wrong, GitHub is awesome, and like a consummate host... but not the way I love me some quick and dirty snippet code, these days. Whatever, you say lazy, I say productively relaxed, potato/potahto.
Erm. In any case please do enjoy this model fixture-exporter. Yes.
Just a dump of a countries data, including standard codes & dial-codes, based on the following model:
- Country
-- name : CharField
-- code : CharField
-- dial_code : CharField
Note that countries aren't unique, as some may have several intl. dial codes.
You can parse it using script or load it using the loaddata command.
*JsonWebService.jsonresponse
JsonWebService provides the property jsonresponse which marks the method it is applied to, and also serializes to json the response of the method.
*JsonWebService.urls
Scans the marked methods and build a urlpattern ready to use in urls.py
Django JSON view decorator. Dumps the object returned from the view function. Allows you to customize the JSON dumps() function using the available keyword arguments available from the simplejson module. By default, indents the output with 4 characters.
I often need to dump data from a database to csv. This little snippet should make it easy enough to do without having to worry too much about character encodings, though it does assume you want your csv file to be utf-8 encoded.
Note that this dumps just one table from the database. Trying to dump all the tables in your app will raise an exception.
**Disclaimer**
This is proof of concept snippet, It can not be considered as best practice. Seems like it's better to store (key => value) in sepetare model with 'key' and 'value' fields.
**Example**
You can assign any dict to model field that can be dumped/serialized with Django json encoder/decoder. Data is saved as TextField in database, empty dict is saved as empty text. Tested with Django 1.2beta.
import DictionaryField
class UserData(models.Model):
user = models.ForeignKey(User)
meta = DictionaryField(blank=True)
There are similar snippets: [JSONField 1](http://www.djangosnippets.org/snippets/377/) or [JSONField 2](http://www.djangosnippets.org/snippets/1478/).
Based on http://www.djangosnippets.org/snippets/592/, a simplified recurse template tag that will explore dict and list objects. Useful and straightforward for JSON documents (for instance from couchdb :p).
Actual usage example:
{% recursedict mydictionary %}
<ul>
{% loop %}
<li>{% if key %}<b>{{ key }}</b>: {% endif %}{% value %}</li>
{% endloop %}
</ul>
{% endrecurse %}
The main tag syntax is "recursedict var" where var is your dictionary name.
The "key" property will contain the current key, or None if the current value comes from a list (in other words the list (a, b, c) is handled like a very hypothetical {None: a, None: b, None: c} dictionary.)
{% value %} will output the current value, or recurse if the value is a list, tuple or dict.
Model field that stores serialized value of model class instance and returns deserialized model instance. Example usage:
from django.db import models
import SerializedObjectField
class A(models.Model):
object = SerializedObjectField(serialize_format='json')
class B(models.Model):
field = models.CharField(max_length=10)
b = B(field='test')
b.save()
a = A()
a.object = b
a.save()
a = A.object.get(pk=1)
a.object
<B: B object>
a.object.__dict__
{'field': 'test', 'id': 1}