This is a Model base class used to support internationalization (i18n) for your models.
This code extends the Django's Model class so you can use all available options from Model safely. Basicly, it uses introspection to create a sub-model to your model to hold translation.
**Features:**
1. Simplicity of use. You simply extend your model with this class and add all the fields that needs to be translated are placed under the `locale` sub-class;
2. The code uses the `django.utils.translation.get_language()` to select the current language;
3. You can use `python ./manage.py syncdb` command safely;
4. Force the user to enter a translation for each language even if the fields can be blank. This makes sure that all objects are returned safely.
**Ordering by locale fields:**
To sort on translated fields, use the form of "model_i18n__transfieldname" (see code for example).
**Limitation:**
Do not use localized fields in __unicode__, the admin will throw an exception when you'll add a new item and do "save and continue".
Just drop a comment if you need more information.
(last update: 06/15/2010)
I found my self doing data migration for a client, and also found that their old system (CSV) had 4 text fields that were 2 to 4MB each and after about 2 minutes of hammering the mysql server as I was parsing this and trying to insert the data the server would drop all connections. In my testing I found that if I didnt send those 4 fields the mysql server was happy to let me migrate all my data all (240GB of it). So I started thinking, "I should just store these fields compress anyways, a little over head to render the data, but thats fine by me."
So thus was born a CompressedTextField. It bz2 compresses the contents then does a base64 encode to play nice with the server storage of text fields. Once I started using this my data migration, though a bit slower then without the field data, ran along all happy.
Requires [PyISBN](http://pypi.python.org/pypi/pyisbn/0.5.2). Use like so:
class Book(models.Model):
title = models.TextField()
isbn = ISBNField()
... the link in the widget can be changed to amazon, borders, you name it.
If the DB version is a 13-digit ISBN, the display box contains the 10-digit,
labeled; and vice-versa.
Generate model data with this django management command!
Data is generated based off of the model field types. And will also correctly generate foreign key's to other randomly generated records for join tables. And generate images with random colors and random words in the image - for image fields.
You can supply quite a few parameters that control how the data is generated. And you can control it per field, per model. Or you can supply your own callable function which you can return your own random data.
**SEE THE DOCS / EXAMPLE IN THE CODE SNIPPET FOR AVAILABLE OPTIONS, AND HOW TO CONTROL GENERATED DATA PARAMETERS**
You can generate data that looks like real content, without having to write fixtures and such. Just generate it!
It can generate data for these types of fields:
EmailField
SlugField
BooleanField
DateField
DateTimeField
TimeField
IntegerField
DecimalField
TextField
CharField
IPAddressField
URLField
SmallIntegerField
PositiveSmallIntegerField
PositiveIntegerField
ImageField
There are also a few callables included that you can use to generate this kind of data:
zip, extended zip, hashkey and uuid
It's also worth noting that I keep this project up to date on my own git repository. There are a few fonts you'll need if you want to generate imaages, included in my git repo.
http://gitweb.codeendeavor.com/?p=dilla.git;a=summary
For a model FK'd to a user or profile, you might want every instance of that thing to appear in your site and in the admin as say "Joe's bucketlist." But if Joe's name is Ross, you want "Ross' bucketlist", not "Ross's bucketlist."
Sometimes its necessary to map your django models to Java Hibernate created tables. Hibernate maps boolean field to bit(1) column instead of tinyint in django.
NOTE: tested for mysql backend only
You have some tree-like structure in your models, for example:
`class MyModel(models.Model):
parent = models.ForeignKey('self', verbose_name=u'Parent', \
null=True, blank=True, related_name='children')
name = models.CharField(u'Раздел', max_lengtch=255)
position = PositiveSmallIntegerField(u'Позиция', default=0)
class Meta:
ordering = ('position',)`
To see it as a tree in admin's object list(you also can sort items, move to another parents by drag-n-drop; and rename them) add this to admin.py:
`class MyModelAdmin(admin.ModelAdmin):
ordering = ('position',)
list_display = ('pk','name','parent','position')
raw_id_fields =('parent',)
list_per_page = 900 #we sould have all objects on one page
list_editable = ('name','position','parent')
def parent_id(self,obj):
return obj.parent and obj.parent.id or '0'
class Meta:
model = MyModel
class Media:
js = [settings.MEDIA_URL + s for s in ('lib/jquery-1.3.2.min.js',
'lib/jquery.tree.min.js',
'lib/plugins/jquery.tree.contextmenu.js',
'lib/mymodel_admin.js',)]
css = {
'all':(settings.MEDIA_URL+'css/nestedsortablewidget.css',)
}`
mymodel_admin.js is the code listed here, if you have different title field(not "name"), change var title_column in javascript, list_display and list_editable.
jstree can be obtained here: [jstree](http://www.jstree.com/)
screenshot is in [my blog](http://tabed.org/blog/2010/01/06/jstree-in-django-admin/)
Runs model methods on save, create, update, delete
Similar to Rails hooks
**Usage:**
*in models.py*
from myproject.hooks import connect_hooks
class MyModel(models.Model):
#...
# only on first save of a newly created object
def before_create(self): print self
def after_create(self): print self
# not on first save of a newly created object
def before_update(self): print self
def after_update(self): print self
# any save, new object or update
def before_save(self): print self
def after_save(self): print self
# delete, self is still available after delete
def before_delete(self): print self
def after_delete(self): print self
**connect_hooks(MyModel)**
You can use `UrlModel` to provide URL functionality to any instance of any model and any language (language support can be removed from this). Each model must have own view method, that returns HttpResponse. I was inspired by Flatpages. It is useful for small sites and static pages.
`class Page(UrlModel):
text = models.TextField()
def view(self, request)
# do something here
return HttpResponse(...)`
This template tag provides an easy way to render objects in your template, even if you don't know ahead of time what type they are.
For example, if you've got a search page with a result list comprised of objects from various models, you can simply loop through them and render them using the tag. The tag will choose the best template and render the object for you.
The tag's docstring has all the details. I hope you find this as useful as I have. Questions, comments, complaints welcome.
[Based on snippet #513 by obeattie.](http://www.djangosnippets.org/snippets/513/)
**Update 10/10/09:** [Further development is now occurring on GitHub, thanks to Shrubbery Software.](http://github.com/shrubberysoft/django-picklefield)
Incredibly useful for storing just about anything in the database (provided it is Pickle-able, of course) when there isn't a 'proper' field for the job.
`PickledObjectField` is database-agnostic, and should work with any database backend you can throw at it. You can pass in any Python object and it will automagically be converted behind the scenes. You never have to manually pickle or unpickle anything. Also works fine when querying; supports `exact`, `in`, and `isnull` lookups. It should be noted, however, that calling `QuerySet.values()` will only return the encoded data, not the original Python object.
*Please note that this is supposed to be two files, one fields.py and one tests.py (if you don't care about the unit tests, just use fields.py).*
This PickledObjectField has a few improvements over the one in [snippet #513](http://www.djangosnippets.org/snippets/513/).
1. This one solves the `DjangoUnicodeDecodeError` problem when saving an object containing non-ASCII data by base64 encoding the pickled output stream. This ensures that all stored data is ASCII, eliminating the problem.
2. `PickledObjectField` will now optionally use `zlib` to compress (and uncompress) pickled objects on the fly. This can be set per-field using the keyword argument "compress=True". For most items this is probably **not** worth the small performance penalty, but for Models with larger objects, it can be a real space saver.
3. You can also now specify the pickle protocol per-field, using the protocol keyword argument. The default of `2` should always work, unless you are trying to access the data from outside of the Django ORM.
4. Worked around a rare issue when using the `cPickle` and performing lookups of complex data types. In short, `cPickle` would sometimes output different streams for the same object depending on how it was referenced. This of course could cause lookups for complex objects to fail, even when a matching object exists. See the docstrings and tests for more information.
5. You can now use the `isnull` lookup and have it function as expected. A consequence of this is that by default, `PickledObjectField` has `null=True` set (you can of course pass `null=False` if you want to change that). If `null=False` is set (the default for fields), then you wouldn't be able to store a Python `None` value, since `None` values aren't pickled or encoded (this in turn is what makes the `isnull` lookup possible).
6. You can now pass in an object as the default argument for the field without it being converted to a unicode string first. If you pass in a callable though, the field will still call it. It will *not* try to pickle and encode it.
7. You can manually import `dbsafe_encode` and `dbsafe_decode` from fields.py if you want to encode and decode objects yourself. This is mostly useful for decoding values returned from calling `QuerySet.values()`, which are still encoded strings.
The tests have been updated to match the added features, but if you find any bugs, please post them in the comments. My goal is to make this an error-proof implementation.
**Note:** If you are trying to store other django models in the `PickledObjectField`, please see the comments for a discussion on the problems associated with doing that. The easy solution is to put django models into a list or tuple before assigning them to the `PickledObjectField`.
**Update 9/2/09:** Fixed the `value_to_string` method so that serialization should now work as expected. Also added `deepcopy` back into `dbsafe_encode`, fixing #4 above, since `deepcopy` had somehow managed to remove itself. This means that lookups should once again work as expected in **all** situations. Also made the field `editable=False` by default (which I swear I already did once before!) since it is never a good idea to have a `PickledObjectField` be user editable.
This Base64Field class can be used as an alternative to a BlobField, which is not supported by Django out of the box.
The base64 encoded data can be accessed by appending _base64 to the field name. This is especially handy when using this field for sending eMails with attachment which need to be base64 encoded anyways.
**Example use:**
class Foo(models.Model):
data = Base64Field()
foo = Foo()
foo.data = 'Hello world!'
print foo.data # will 'Hello world!'
print foo.data_base64 # will print 'SGVsbG8gd29ybGQh\n'
We currently use two-level tuples to specify choices of a field in models or forms.
But, because it has only (value, verbose name) pair, the readability is bad whenever we indicate a specific choice value in our Python codes.
So I made a small class that does "magic" for this: A Named Enumeration.
Instead of `myobj.status == 0`, use `myobj.status == STATUS.UNREVIEWED`, for example.