Dumps DB data for each application to that application's fixtures directory.
For example:
$ ./manage.py dump_app_data
...
$ hg status
M apps/foo/fixtures/dev.json
M apps/bar/fixtures/dev.json
This lets you load global fixtures from a directory you set as `FIXTURES_ROOT` in your settings.py.
For example, setting `FIXTURES_ROOT` to `/path/to/myproject/fixtures/`
I tend to like to keep fixtures that should be loaded when a new instance of a site is deployed, but not auto-loaded (so they won't rewrite any data that comes after), in a project-level fixtures directory like this.
Sometimes these fixtures can be useful in your test suites, so this is a convenient way to load them.
Usage:
`load_global_fixtures('sites.json', 'contacts.json')`
`load_global_fixtures('sites.json', 'contacts.json', fixtures_root='/some/other/path', verbosity=1)`
Sometimes you need to store information that the server needs in unencrypted form (e.g. OAuth keys and secrets), but you don't really want to leave it lying around in the open on your server. This snippet lets you split that information into two parts:
* a securing passphrase, stored in the Django settings file (or at least made available via that namespace)
* the actual secret information, stored in the ORM database
Obviously, this isn't as secure as using a full blown key management system, but it's still a significant step up from storing the OAuth keys directly in the settings file or the database.
Note also that these fields will be displayed unencrypted in the admin view unless you add something like the following to ``admin.py``:
from django.contrib import admin
from django import forms
from myapp.fields import EncryptedCharField
class MyAppAdmin(admin.ModelAdmin):
formfield_overrides = {
EncryptedCharField: {'widget': forms.PasswordInput(render_value=False)},
}
admin.site.register(PulpServer, PulpServerAdmin)
If Django ever acquires a proper binary data type in the default ORM then the base64 encoding part could be skipped.
This snippet is designed to be compatible with the use of the South database migration tool *without* exposing the passphrase used to encrypt the fields in the migration scripts. (A migration tool like South also allows you to handle the process of *changing* the passphrase, by writing a data migration script that decrypts the data with the old passphrase then writes it back using the new one).
Any tips on getting rid of the current ugly prefix hack that handles the difference between deserialising unencrypted strings and decrypting the values stored in the database would be appreciated!
Sources of inspiration:
[AES encryption with M2Crypto](http://passingcuriosity.com/2009/aes-encryption-in-python-with-m2crypto/)
[EncryptedField snippet](http://djangosnippets.org/snippets/1095/) (helped me improve several Django-specific details)
These decorators can be used to make some model/form fields readonly.
**Sample usage:**
# Use this decorator on form with readonly fields.`
@modelform_with_readonly_fields`
class FooAdminForm(forms.ModelForm):`
...
# This decorator shoud be used to protect selected fields `
# from modification after initial save.`
@has_readonly_fields`
class Foo(models.Model):`
read_only_fields = ('name', )`
...
**Result** will be the same as shown in this post: [Readonly field](http://stackoverflow.com/questions/324477/in-a-django-form-how-to-make-a-field-readonly-or-disabled-so-that-it-cannot-be/1424453#1424453) and
[Readonly model field](http://www.djangozen.com/blog/read-only-fields-in-models)
Loading templates by path
app.template_name -> app/templates/template_name.html
app.subdir.template_name -> app/templates/subdir/template_name.html
Usage:
append in settings.TEMPLATE_LOADERS
and using render_to('app.index', context)
This snippet uses the admin FilterSelectMultiple widget in normal forms.
Earlier I tried this without the **internationalization javascript** and failed, so I looked around the web and found couple of posts, they worked but suggest many customizations.
I learnt from them that they had this *jsi18n* javascript included. I included it with mine and it worked.
I have written a [detailed post](http://www.rohanjain.in/coding/2011/06/20/django-using-admin-horizontal-filter-in-forms/) about this.
From: [incredible times](http://incredibletimes.org)
With inspiration from: [Unethical Blogger](http://unethicalblogger.com/2008/05/03/parsing-html-with-python.html)
This code parses any provided HTML content, and extracts a number of paragraphs specified, with all the content and tags inside them.
Example:
Template variable "content" contains:
<a href="#>some text</a>
<p><strong>Testing</strong>testing testing this is a tester's life</p>
<div>I wont see the world</div>
<p>Another paragraph</p>
So, place this code in any loaded template module (inside a templatetags folder of your app... i.e. myapp/templatetags/myutils.py)
{% load myutils %}
{{ content|paragraphs:"1"}}
Would return:
<p><strong>Testing</strong>testing testing this is a tester's life</p>
Whereas
{% load myutils %}
{{ content|paragraphs:"2"}}
Returns:
<p><strong>Testing</strong>testing testing this is a tester's life</p>
<p>Another paragraph</p>
I find Django's default YAML serializer output too repetitive, so I came up with this customized version that avoids outputting the model name for every single object, and makes the primary key into an index for the object's fields. This allows many simple model instances to be serialized as one-liners.
See the module docstring for additional explanation and usage notes.
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.
This is a model that implements (most of) the python dictionary interface. Meaning, you can work with this model exactly like a python dictionary, and it handles querying the database for it's values, saving/deleting the helper objects, etc.
I wrote this originally when I needed to store an arbitrary dictionary in the database, and decided to work it up into a near-complete implementation of a dictionary.
In order to make sure that the dictionary is the most optimized possible, I have a static method that can be used for retrieval. Feel free to ignore it if you don't care about optimizing database queries.
Here's an example:
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from binder.models import Dictionary
>>> d = Dictionary.getDict('Foobar')
>>> print d
{u'Foobar': u'omgbbq', u'HAHAHAH': u"who's afraid of a big, black, bat?"}
>>> d['pot'] = 'The kettle is black.'
>>> print d
{u'Foobar': u'omgbbq', u'pot': u'The kettle is black.', u'HAHAHAH': u"who's afraid of a big, black, bat?"}
>>> print d['pot']
The kettle is black.
>>> for k, v in d.iteritems():
... print k +":", v
...
Foobar: omgbbq
HAHAHAH: who's afraid of a big, black, bat?
pot: The kettle is black.
>>> print d.keys()
[u'Foobar', u'HAHAHAH', u'pot']
>>> print d.values()
[u'omgbbq', u"who's afraid of a big, black, bat?", u'The kettle is black.']
>>>
There's several more functions that I've implemented; check the code to see. (An interesting note: DictField saves immediately upon making a change, which is good to keep in mind in case that functionality isn't expected.)
Hope someone finds this useful. :)
--Chris
You're looking at the top-rated snippets currently on the site; if you'd like to contribute, sign up for an account and you'll be able to rate any snippet you see.