Add fields and extend Django's built-in `Group` model using a `OneToOneField` (i.e. a profile model). In this example, we add a `UUIDField`. Whenever a new group is created, we automatically (via signals) create a corresponding `Role` record referencing the newly created group. Whenever a Group is deleted, the corresponding Role is deleted as well.
The code was placed inside a helper file without using a class. The Django validator was not designed to work with validator classes, it would appear, so retrieving the value from the field proved to be a hassle. Just create a helper file, import it on your model, and use the validator in the standard way, as such:
cnpj = models.CharField(unique=True, max_length=14, validators=[validate_CNPJ])
cpf = models.CharField(unique=True, max_length=14, validators=[validate_CPF])
Provides UUIDField for your models. This version creates very short UUID represenation (21 chars) when the record is added eg. in admin. Generated ids are safe to be used in URLs.
You can put represent it in admin as
'readonly_fields=("uuid",)'
**[Improved and Released as Save The Change.](https://github.com/karanlyons/django-save-the-change)**
Django 1.5 added the `update_fields` `kwarg` to `Model.save()`, which allows the developer to specify that only certain fields should actually be committed to the database. However, Django provides no way to automatically commit only changed fields if they're not specified.
This mixin keeps track of which fields have changed from their value in the database, and automatically applies `update_fields` to update only those fields.
Sometimes we may need to generate a *ModelChoiceField* in which choices are generated at runtime, depending on the locale language. The snippet generates a *ChoiceField* based on a queryset and a specific attribute of the Model, ordering the choices by the attribute content in the locale language.
**Usage example** (inside a form declaration)
country = LazyModelChoiceField(sort_by='name', queryset = \
Country.objects.all, empty_label=_('All countries'), label=_('Country'))
Based on lsbardel LazyChoiceField implementation (snippet 1767)
Overridden save() method that adds Gravatar support for a user with a profile photo field (and presumably an email field). Checks to see if user has provided a photo. If not, then query Gravatar for a possible photo. Finally, if Gravatar does not have an appropriate photo for this user, then use whatever default photo is available (in this case, 'users/photos/default_profile_photo.png'... change as necessary).
This snippet *updates* http://www.djangosnippets.org/snippets/383/ and http://www.djangosnippets.org/snippets/1495/ for Django 1.4+, and adds support for sqlite3 and south. Original snippet text: A CompressedTextField to transparently save data gzipped in the database and uncompress at retrieval.
This management command is run like this: `./manage.py -a someapp filename.cfg`
it looks in `someapp`'s directory for a file called `/config/filename.cfg` with the format explained in the help text, and creates the model instances described in the config file.
It uses the configobj module.
this would be an example config file:
[project.Profile]
[[fields]]
receive_notifications = False
[[children]]
[[[auth.User]]]
[[[[fields]]]]
username = AnnonymousUser
password = ! # set unusable password. There's no way yet to hash and set a given password
email = [email protected]
Daniel Roseman's snippet, updated will all fixes mentioned in the comments of the first version + some other things to make it work under Django 1.4.
South, and dumpdata are working.
There's an ugly int(....) at the validate function in order to cast each value as an integer before comparing it to default choices : I needed this, but if you're storing strings values, just remove the int(......) wrapper.
-------------------------------------
Orginal readme
Usually you want to store multiple choices as a manytomany link to another table. Sometimes however it is useful to store them in the model itself. This field implements a model field and an accompanying formfield to store multiple choices as a comma-separated list of values, using the normal CHOICES attribute.
You'll need to set maxlength long enough to cope with the maximum number of choices, plus a comma for each.
The normal get_FOO_display() method returns a comma-delimited string of the expanded values of the selected choices.
The formfield takes an optional max_choices parameter to validate a maximum number of choices.
Intro
-----
I found a question on SO for which Justin Lilly's answer was correct but not as thorough as I'd like, so I ended up working on a simple snippet that shows how to bind signals at runtime, which is nifty when you want to bind signals to an abstract class.
Bonus: simple cache invalidation!
Question
--------
[How do I use Django signals with an abstract model?](http://stackoverflow.com/questions/2692551/how-do-i-use-django-signals-with-an-abstract-model)
I have an abstract model that keeps an on-disk cache. When I delete the model, I need it to delete the cache. I want this to happen for every derived model as well.
If I connect the signal specifying the abstract model, this does not propagate to the derived models:
pre_delete.connect(clear_cache, sender=MyAbstractModel, weak=False)
If I try to connect the signal in an init, where I can get the derived class name, it works, but I'm afraid it will attempt to clear the cache as many times as I've initialized a derived model, not just once.
Where should I connect the signal?
Answer
------
I've created a custom manager that binds a post_save signal to every child of a class, be it abstract or not.
This is a one-off, poorly tested code, so beware! It works so far, though.
In this example, we allow an abstract model to define CachedModelManager as a manager, which then extends basic caching functionality to the model and its children. It allows you to define a list of volatile keys that should be deleted upon every save (hence the post_save signal) and adds a couple of helper functions to generate cache keys, as well as retrieving, setting and deleting keys.
This of course assumes you have a cache backend setup and working properly.
This class decorator will help you when you want to keep a unique boolean (think a 'default' field which should only be only one set to true in a group).
The interesting thing with this, is that it's possible to assign a subset of fields to be used, so that the uniqueness of the field will be guaranteed among only the subset (look at the Example section in the code to understand this behaviour).
This is a better and improved way of doing http://djangosnippets.org/snippets/2676/
Django allows you to specify your own ModelManager with custom methods. However, these methods are chainable. That is, if you have a method on your PersonManager caled men(), you can't do this:
Person.objects.filter(birth_date__year=1978).men()
Normally, this isn't a problem, however your app may be written to take advantage of the chainability of querysets. For example, you may have an API method which may return a filtered queryset. You would want to call with_counts() on an already filtered queryset.
In order to overcome this, we want to override django's QuerySet class, and then make the Manager use this custom class.
The only downside is that your functions will not be implemented on the manager itself, so you'd have to call `Person.objects.all().men()` instead of `Person.objects.men()`. To get around this you must also implement the methods on the Manager, which in turn call the custom QuerySet method.
Useful when you want to keep only one instance of a model to be the default one.
This is a decorative way of doing the same as in http://djangosnippets.org/snippets/1830/
Can this be made better as a class decorator (not having to declare explicitly the save method) ?