Source code for django_utils.base_models
import six
from django.db.models import base
from django.db import models
from django.template import defaultfilters
from python_utils import formatters
[docs]class ModelBase(six.with_metaclass(ModelBaseMeta, models.Model)):
[docs]class CreatedAtModelBase(ModelBase):
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
[docs]class NameMixin(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'
'''
def __unicode__(self):
return self.name
def __str__(self):
out = self.__unicode__()
if six.PY2:
out = out.encode('utf-8', 'replace')
return out
def __repr__(self):
repr_ = six.text_type('<%s[%d]: %s>') % (
self.__class__.__name__,
self.pk or -1,
self.name,
)
if six.PY2:
repr_ = repr_.encode('utf-8')
return repr_
[docs]class SlugMixin(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'
'''
[docs] def save(self, *args, **kwargs):
if not self.slug and self.name:
self.slug = defaultfilters.slugify(self.name)
super(NameMixin, self).save(*args, **kwargs)