Skip to main content

A collection of utilities that make dealing with Django models more fun.

Project description

Installation
------------

1. `pip install -e git+git://github.com/hzdg/django-modeltools.git#egg=django-modeltools`


Included Tools
-----


### Enum

The `Enum` class lets you quickly define enumeration types for model field
values. It uses [Pep 435][1]-style enums, but has some extra model-specific
functionality (like the ability to easily add custom labels).


[1]: http://www.python.org/dev/peps/pep-0435/


#### Usage

In models.py:

from modeltools import Enum, EnumField

class MyModel(models.Model):

class Color(Enum):
RED = 'r'
GREEN = 'g'
BLUE = 'b'

color = models.EnumField(Color)

Elsewhere:

m = MyModel.objects.filter(color=MyModel.Color.RED)


#### Custom Labels

By default, labels are title-cased versions of your enum member names (e.g.
"Red" for `Color.RED`). You can customize this with an inner `Labels` class.

class Color(Enum):
RED = 'r'
GREEN = 'g'
BLUE = 'b'

class Labels:
RED = 'El color del diablo'


#### Ordering

Members aren't automatically ordered in Python 2.X enums. You have to do it
yourself using an `__order__` attribute.

class Color(Enum):
__order__ = 'RED GREEN BLUE'

RED = 'r'
GREEN = 'g'
BLUE = 'b'


### format_filename

The `format_filename` function provides an easy way to name user media (uploaded files) based on properties of the model that stores them.

#### Usage

In models.py:

from modeltools import format_filename as _ff

class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
middle_name = models.CharField(max_length=50)
avatar = models.ImageField(upload_to=_ff('avatars/{last_name}_{first_name}'))

In the above example, `{first_name}` and `{last_name}` will be replaced with the corresponding values from the `Person` instance. The uploaded file will automatically retain its original extension.

upload_to=_ff('avatars/{last_name}_{first_name}/{__filename}.thumbnail{__ext}')

`{__filename}` and `{__ext}` allows access to the name and extension the file was uploaded with.

By default, the properties used in the formatting pattern will be converted to lowercase, stripped of non-word characters, and have their spaces replaced with underscores. (This behavior can be changed by providing extra arguments to the `format_filename` function.) The rest of the formatting string will be unaffected.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-modeltools-1.0.0.tar.gz (6.1 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page