This utility makes a text dump of a model instance, including objects related by a forward or reverse foreign key. The result is a hierarchical data structure where
* each instance is represented as a list of fields,
* each field as a (<name>, <value>) tuple,
* each <value> as a primitive type, a related object (as a list of fields), or a list of related objects.
See the docstring for examples.
We used this to make text dumps of parts of the database before and after running a batch job. The format was more useful than stock `dumpdata` output since all related data is included with each object. These dumps lend themselves particularly well for comparison with a visual diff tool like [Meld](http://meldmerge.org/).
If you inherit from ValidatedModel instead of from models.Model, then full_clean() will be called before save().
So, add validators to your field definitions, and all your fields will be validated before they go to the database.
The same thing can be accomplished with a pre_save signal, but the code is quite a bit messier than the simple inheritance above.
Out of the box, Django e-mail fields for both database models and forms only accept plain e-mail addresses. For example, `[email protected]` is accepted.
On the other hand, full e-mail addresses which include a human-readable name, for example the following address fails validation in Django:
Joe Hacker <[email protected]>
This package adds support for validating full e-mail addresses.
**Database model example**
from django import models
from full_email.models import FullEmailField
class MyModel(models.Model):
email = FullEmailField()
**Forms example**
from django import forms
from full_email.formfields import FullEmailField
class MyForm(forms.Form):
email = FullEmailField(label='E-mail address')
I maintain this code in a [GitHub gist](https://gist.github.com/1505228). It includes some unit tests as well.
Simple password validation for user registration - requires that password be 7 or more characters and contain both letters and numbers. Original validation with regex approach developed by kurtis. Optimized no-regex version based on code from watchedman ran as fast or significantly faster on all systems on which we tested it.
When you want to save integers to the db, you usually have the choice between 16-, 32- and 64-bit Integers (also 8- and 24-bit for MySQL). If that doesn't fit your needs and you want to use your db-memory more efficient, this field might be handy to you.
Imagine you have 3 numbers, but need only 10 bit to encode each (i.e. from 0 to 1000). Instead of creating 3 smallint-fields (48 bit), you can create one 'ByteSplitterField' which implements 3 'subfields' and automatically encodes them inside a 32 bit integer. You don't have to take care how each 10-bit chunk is encoded into the 32-bit integer, it's all handled by the field (see also field's description).
Additionally, the Field offers opportunity to use decimal_places for each of your subfields. These are 'binary decimal places', meaning the integer-content is automatically divided by 2, 4, 8, etc. when you fetch the value from the field.
You can also specify how values are rounded ('round' parameter) and what happens when you try to save a value out of range ('overflow' parameter)
Not implemented (maybe in the future if I should need it sometime):
* signed values. All values are positive right now!
* real (10-based) decimal places (actually you could probably directly use DecimalFields here)
* further space optimization, i.e. saving into CharField that's length can be chosen byte-wise
Django lacks support of MySQL's "tinyint" 8-bit-integer datatype. This snippet gives you a TinyIntegerField and a PositiveTinyIntegerField. Falls back Django's SmallIntegerField if a different database-engine is used
Needed a function to check if any field in an instance has changed. If so update a datetime field to now to keep track of changes. This function is an override of the save function in the model.
To put obfuscated primary keys in any class, simply inherit from this one. For example:
class Offer(ObfuscatedPKModel)
You can match for these bigint primary keys in your urls.py like this:
'^offer/(?P<offer_pk>[0-9\-]+)$'
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)
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
This code provides a mixin and decorator which, when used together, can provide advisory locking on model methods. It provides locking by using MySQL's advisory lock system. See the example at the bottom of the code.
This is a convenient and easy way to guarantee your model methods have exclusive access to a model instance.
The LockableObjects class requires a MySQL backend, but it could be modified to use other back-end locking systems.
The lock name generation in `LockableObject.get_lock_name()` could be altered to create much more complex locking schemes. Locking per-object, per-method for example..
Lock attempts have a timeout value of 45 seconds by default. If a timeout occurs, EnvironmentError is raised.
**See the bottom of the script for an example**
> **Instructions:**
* **1:** Place the code in locking.py somewhere in your path
* **2:** In your models.py (or any script with an object you want to lock):
`from locking import LockableObject, require_object_lock`
* **3:** In the model you want locking for, add the `LockableObject` mixin
* **4:** Decorate the method you want to be exclusively locked with `@require_object_lock`
This class makes easier the job of rendering lists of model instances in django templates. It's intended to mimic the behavior of the Model Forms in that it contains the code needed to render it as an HTML table and makes it easy to handle all the model lists from a single view (as it's usually done with the generic views for creating and updating model instances).
It also supports pagination and provides hooks for subclassing and customizing the rendered fields, column titles and list order.
Basic example:
`class Account(Model):`
`name = models.CharField(max_length=MAX_LENGTH)`
`responsible = models.CharField(max_length=MAX_LENGTH)`
`email = models.EmailField()`
`class AccountModelList(ModelList):`
`class Meta:`
`model = Account`
`fields = ['name', 'responsible'] #email won't get a column`
The model list would be instantiated with something like:
`model_list = AccountModelList(instances=account_queryset)`
Then a table header can be rendered with model_list.as_table_header(), while the table rows can be rendered calling as_table() on each model_list.items element.
Nice to name your constant multiple choice fields in models, this is one way of doing that. Sorry I haven't looked into existing alternatives. But this approach worked for me.