Welcome to Django Utils’s documentation!¶
Contents:
Introduction¶
Travis status:

Coverage:

Django Utils is a collection of small Django helper functions, utilities and classes which make common patterns shorter and easier. It is by no means a complete collection but it has served me quite a bit in the past and I will keep extending it.
Examples are:
- Enum based choicefields
- Models with automatic __str__, __unicode__ and __repr__ functions based on names and/or slugs using simple mixins.
- Models with automatic updated_at and created_at fields
- Models with automatic slugs based on the name property.
- Iterating through querysets in predefined chunks to prevent out of memory errors
The library depends on the Python Utils library.
Documentation is available at: http://django-utils-2.readthedocs.io/en/latest/
Install¶
To install:
- Run pip install django-utils2 or execute python setup.py install in the source directory
- Add django_utils to your INSTALLED_APPS
If you want to run the tests, run py.test (requirements in tests/requirements.txt)
Usage¶
To enable easy to use choices which are more convenient than the Django 3.0 choices system you can use this:
from django_utils import choices
# For manually specifying the value (automatically detects `str`, `int` and `float`):
class Human(models.Model):
class Gender(choices.Choices):
MALE = 'm'
FEMALE = 'f'
OTHER = 'o'
gender = models.CharField(max_length=1, choices=Gender)
# To define the values as `male` implicitly:
class Human(models.Model):
class Gender(choices.Choices):
MALE = choices.Choice()
FEMALE = choices.Choice()
OTHER = choices.Choice()
gender = models.CharField(max_length=1, choices=Gender)
# Or explicitly define them
class Human(models.Model):
class Gender(choices.Choices):
MALE = choices.Choice('m', 'male')
FEMALE = choices.Choice('f', 'female')
OTHER = choices.Choice('o', 'other')
gender = models.CharField(max_length=1, choices=Gender)
A PostgreSQL ENUM field will be coming soon to automatically facilitate the creation of the enum if needed.
Links¶
- Documentation
- Bug reports
- Package homepage
- My blog
django_utils package¶
Subpackages¶
django_utils.management package¶
Subpackages¶
django_utils.management.commands package¶
-
class
django_utils.management.commands.admin_autogen.
Command
[source]¶ Bases:
django_utils.management.commands.base_command.CustomBaseCommand
-
class
django_utils.management.commands.base_command.
CustomAppCommand
[source]¶ Bases:
django_utils.management.commands.base_command.CustomBaseCommand
,django.core.management.base.AppCommand
-
class
django_utils.management.commands.settings.
Command
[source]¶ Bases:
django_utils.management.commands.base_command.CustomBaseCommand
-
can_import_settings
= True¶
-
help
= 'Get a list of the current settings, any arguments given will be\n used to match the settings name (case insensitive).\n '¶
-
output_types
= ['pprint', 'print', 'json', 'csv']¶
-
requires_model_validation
= False¶
-
Module contents¶
django_utils.templatetags package¶
Submodules¶
django_utils.templatetags.debug module¶
Bases:
django_utils.templatetags.debug._Formatter
Call the formatter with the given value to format and optional depth
>>> formatter = Formatter() >>> class Eggs: pass >>> formatter(Eggs) '<Eggs {}>'
Format a date
Parameters: - value – a date to format
- depth – the current depth
Returns: a formatted string
>>> formatter = Formatter() >>> formatter(datetime.date(2000, 1, 2)) '<date:2000-01-02>' >>> formatter(datetime.datetime(2000, 1, 2, 3, 4, 5, 6)) '<datetime:2000-01-02 03:04:05.000006>'
Format a string
Parameters: - value – a str value to format
- depth – the current depth
Returns: a formatted string
>>> formatter = Formatter() >>> formatter({'a': 1, 'b': 2}, 5) '{a: 1, b: 2}'
Format an integer/long
Parameters: - value – an int/long to format
- depth – the current depth
Returns: a formatted string
>>> formatter = Formatter() >>> str(formatter(1, 0)) '1' >>> formatter(1, 1) '1'
Format a string
Parameters: - value – a list to format
- depth – the current depth
Returns: a formatted string
>>> formatter = Formatter() >>> formatter(list(range(5))) '[0, 1, 2, 3, 4]'
Format a string
Parameters: - value – a str value to format
- depth – the current depth
Returns: a formatted string
>>> formatter = Formatter() >>> from django.contrib.auth.models import User >>> user = User() >>> del user.date_joined >>> str(formatter(user, 5, show_protected=False)[:30]) '<User {email: , first_name: , '
Format an object
Parameters: - value – an object to format
- depth – the current depth
Returns: a formatted string
>>> formatter = Formatter() >>> original_max_length = formatter.MAX_LENGTH >>> formatter.MAX_LENGTH = 50
>>> class Spam(object): ... x = 1 ... _y = 2 ... __z = 3 ... __hidden_ = 4 >>> spam = Spam()
>>> str(formatter(spam, show_protected=True, show_special=True)) '<Spam {x: 1, _Spam__hidden_: 4, _Spam__z: 3, __dict__:...}>' >>> str(formatter(spam, show_protected=False, show_special=False)) '<Spam {x: 1}>'
>>> formatter.MAX_LENGTH = original_max_length
Format a string
Parameters: - value – a str value to format
- depth – the current depth
Returns: a formatted string
>>> formatter = Formatter() >>> str(formatter('test')) 'test' >>> str(formatter(six.b('test'))) 'test'
Format a string
Parameters: - value – a unicode value to format
- depth – the current depth
Returns: a formatted string
>>> formatter = Formatter() >>> original_max_length = formatter.MAX_LENGTH >>> formatter.MAX_LENGTH = 10 >>> str(formatter('x' * 11)) 'xxxxxxx...' >>> formatter.MAX_LENGTH = original_max_length
Debug template filter to print variables in a pretty way
>>> str(debug(123).strip()) '<pre style="border: 1px solid #fcc; background-color: #ccc;">123</pre>'
Module contents¶
Submodules¶
django_utils.base_models module¶
-
class
django_utils.base_models.
CreatedAtModelBase
(*args, **kwargs)[source]¶ Bases:
django_utils.base_models.ModelBase
-
created_at
¶ A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
-
get_next_by_created_at
(**morekwargs)¶
-
get_next_by_updated_at
(**morekwargs)¶
-
get_previous_by_created_at
(**morekwargs)¶
-
get_previous_by_updated_at
(**morekwargs)¶
-
updated_at
¶ A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
-
-
class
django_utils.base_models.
ModelBase
(*args, **kwargs)[source]¶ Bases:
django.db.models.base.Model
-
class
django_utils.base_models.
ModelBaseMeta
[source]¶ Bases:
django.db.models.base.ModelBase
Model base with more readable naming convention
Example: Assuming the model is called app.FooBarObject
Default Django table name: app_foobarobject Table name with this base: app_foo_bar_object
-
class
django_utils.base_models.
NameCreatedAtModelBase
(*args, **kwargs)[source]¶ Bases:
django_utils.base_models.NameModelBase
,django_utils.base_models.CreatedAtModelBase
-
get_next_by_created_at
(**morekwargs)¶
-
get_next_by_updated_at
(**morekwargs)¶
-
get_previous_by_created_at
(**morekwargs)¶
-
get_previous_by_updated_at
(**morekwargs)¶
-
-
class
django_utils.base_models.
NameMixin
[source]¶ Bases:
object
Mixin to automatically get a unicode and repr string base on the name
>>> x = NameMixin() >>> x.pk = 123 >>> x.name = 'test' >>> repr(x) '<NameMixin[123]: test>' >>> str(x) 'test' >>> str(six.text_type(x)) 'test'
-
class
django_utils.base_models.
NameModelBase
(*args, **kwargs)[source]¶ Bases:
django_utils.base_models.NameMixin
,django_utils.base_models.ModelBase
-
name
¶ A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
-
-
class
django_utils.base_models.
SlugCreatedAtModelBase
(*args, **kwargs)[source]¶ Bases:
django_utils.base_models.SlugModelBase
,django_utils.base_models.CreatedAtModelBase
-
get_next_by_created_at
(**morekwargs)¶
-
get_next_by_updated_at
(**morekwargs)¶
-
get_previous_by_created_at
(**morekwargs)¶
-
get_previous_by_updated_at
(**morekwargs)¶
-
-
class
django_utils.base_models.
SlugMixin
[source]¶ Bases:
django_utils.base_models.NameMixin
Mixin to automatically slugify the name and add both a name and slug to the model
>>> x = NameMixin() >>> x.pk = 123 >>> x.name = 'test' >>> repr(x) '<NameMixin[123]: test>' >>> str(x) 'test' >>> str(six.text_type(x)) 'test'
-
class
django_utils.base_models.
SlugModelBase
(*args, **kwargs)[source]¶ Bases:
django_utils.base_models.SlugMixin
,django_utils.base_models.NameModelBase
-
slug
¶ A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
-
django_utils.choices module¶
Usage¶
Create a Choices
class and add Choice
objects to the
class to define your choices.
Example with explicit values:¶
The normal Django version:
class Human(models.Model):
GENDER = (
('m', 'Male'),
('f', 'Female'),
('o', 'Other'),
)
gender = models.CharField(max_length=1, choices=GENDER)
The Django Utils Choices version:
from django_utils import choices
class Human(models.Model):
class Gender(choices.Choices):
Male = choices.Choice('m')
Female = choices.Choice('f')
Other = choices.Choice('o')
gender = models.CharField(max_length=1, choices=Gender)
To reference these properties:
Human.create(gender=Human.Gender.Male)
Example with implicit values:¶
The normal Django version:
class SomeModel(models.Model):
SOME_ENUM = (
(1, 'foo'),
(2, 'bar'),
(3, 'spam'),
(4, 'eggs'),
)
enum = models.IntegerField(choices=SOME_ENUM, default=1)
The Django Utils Choices version:
from django_utils import choices
class SomeModel(models.Model):
class Enum(choices.Choices):
Foo = choices.Choice()
Bar = choices.Choice()
Spam = choices.Choice()
Eggs = choices.Choice()
enum = models.IntegerField(
choices=Enum, default=Enum.Foo)
To reference these properties:
SomeModel.create(enum=SomeModel.Enum.Spam)
-
class
django_utils.choices.
Choice
(value=None, label=None)[source]¶ Bases:
object
The choice object has an optional label and value. If the value is not given an autoincrementing id (starting from 1) will be used
>>> choice = Choice('value', 'label') >>> choice <Choice[1]:label> >>> str(choice) 'label'
>>> choice = Choice() >>> choice <Choice[2]:None> >>> str(choice) 'None'
-
order
= 0¶
-
-
class
django_utils.choices.
Choices
[source]¶ Bases:
object
The choices class is what you should inherit in your Django models
>>> choices = Choices() >>> choices.choices[0] Traceback (most recent call last): ... KeyError: 'Key 0 does not exist' >>> choices.choices OrderedDict() >>> str(choices.choices) 'OrderedDict()' >>> choices.choices.items() [] >>> choices.choices.keys() [] >>> choices.choices.values() [] >>> list(choices) []
>>> class ChoiceTest(Choices): ... a = Choice() >>> choices = ChoiceTest() >>> choices.choices.items() [(0, <Choice[...]:a>)] >>> choices.a 0 >>> choices.choices['a'] <Choice[...]:a> >>> choices.choices[0] <Choice[...]:a> >>> choices.choices.keys() [0] >>> choices.choices.values() ['a'] >>> list(choices) [(0, <Choice[...]:a>)] >>> list(ChoiceTest) [(0, <Choice[...]:a>)]
-
choices
= OrderedDict()¶
-
-
class
django_utils.choices.
ChoicesDict
[source]¶ Bases:
object
The choices dict is an object that stores a sorted representation of the values by key and database value
-
class
django_utils.choices.
ChoicesMeta
[source]¶ Bases:
type
The choices metaclass is where all the magic happens, this automatically creates a ChoicesDict to get a sorted list of keys and values
-
class
django_utils.choices.
LiteralChoices
[source]¶ Bases:
django_utils.choices.Choices
Special version of the Choices class that uses the label as the value
>>> class Role(LiteralChoices): ... admin = Choice() ... user = Choice() ... guest = Choice()
>>> Role.choices.values() ['admin', 'user', 'guest'] >>> Role.choices.keys() ['admin', 'user', 'guest']
>>> class RoleWithImplicitChoice(LiteralChoices): ... ADMIN = 'admin' ... USER = 'user' ... GUEST = 'guest'
>>> Role.choices.values() ['admin', 'user', 'guest'] >>> Role.choices.keys() ['admin', 'user', 'guest'] >>> Role.admin 'admin'
-
choices
= OrderedDict()¶
-
django_utils.fields module¶
django_utils.queryset module¶
-
django_utils.queryset.
queryset_iterator
(queryset, chunksize=1000, getfunc=<built-in function getattr>)[source]¶ ‘’ Iterate over a Django Queryset ordered by the primary key
This method loads a maximum of chunksize (default: 1000) rows in it’s memory at the same time while django normally would load all rows in it’s memory. Using the iterator() method only causes it to not preload all the classes.
Note that the implementation of the iterator does not support ordered query sets.
django_utils.view_decorators module¶
-
exception
django_utils.view_decorators.
ViewError
[source]¶ Bases:
exceptions.Exception
-
django_utils.view_decorators.
env
(function=None, login_required=False, response_class=<class 'django.http.response.HttpResponse'>)[source]¶ View decorator that automatically adds context and renders response
Keyword arguments: login_required – is everyone allowed or only authenticated users
Adds a RequestContext (request.context) with the following context items: name – current function name
Stores the template in request.template and assumes it to be in <app>/<view>.html