Top

telemeta.models.enum module

# -*- coding: utf-8 -*-
# Copyright (C) 2007-2010 Samalyse SARL

# This file is part of Telemeta.

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Authors: Olivier Guilyardi <olivier@samalyse.com>
#          David LIPSZYC <davidlipszyc@gmail.com>

from telemeta.models.core import *
from django.utils.translation import ugettext_lazy as _


class Enumeration(ModelCore):
    "Abstract enumerations base class"

    value = CharField(_('value'), required=True, unique=True)
    notes = TextField(_('notes'))

    def __unicode__(self):
        return self.value

    class Meta(MetaCore):
        abstract = True


class MetaEnumeration(MetaCore):
    ordering = ['value']


class EnumerationProperty(ModelCore):

    enumeration_name = models.CharField(_('enumeration name'), max_length=255)
    is_hidden = BooleanField(_('is hidden'), default=False)
    is_admin = BooleanField(_('is admin'), default=True)

    class Meta(MetaCore):
        verbose_name = _("enumeration property")
        verbose_name_plural = _("enumeration properties")

    def __unicode__(self):
        return self.enumeration_name


class PhysicalFormat(Enumeration):
    "Collection physical format"

    class Meta(MetaEnumeration):
        db_table = 'physical_formats'
        verbose_name = _("archive format")


class PublishingStatus(Enumeration):
    "Collection publishing status"

    class Meta(MetaEnumeration):
        db_table = 'publishing_status'
        verbose_name = _("secondary edition")


class AcquisitionMode(Enumeration):
    "Mode of acquisition of the collection"

    class Meta(MetaEnumeration):
        db_table = 'acquisition_modes'
        verbose_name = _("mode of acquisition")


class MetadataAuthor(Enumeration):
    "Collection metadata author"

    class Meta(MetaEnumeration):
        db_table = 'metadata_authors'
        verbose_name = _("record author")


class MetadataWriter(Enumeration):
    "Collection metadata writer"

    class Meta(MetaEnumeration):
        db_table = 'metadata_writers'
        verbose_name = _("record writer")


class LegalRight(Enumeration):
    "Collection legal rights"

    class Meta(MetaEnumeration):
        db_table = 'legal_rights'
        verbose_name = _("legal rights")


class RecordingContext(Enumeration):
    "Collection recording context"

    class Meta(MetaEnumeration):
        db_table = 'recording_contexts'
        verbose_name = _("recording context")

class AdConversion(Enumeration):
    "Collection digital to analog conversion status"

    class Meta(MetaEnumeration):
        db_table = 'ad_conversions'
        verbose_name = _("A/D conversion")

class VernacularStyle(Enumeration):
    "Item vernacular style"

    class Meta(MetaEnumeration):
        db_table = 'vernacular_styles'
        verbose_name = _("vernacular style")

class GenericStyle(Enumeration):
    "Item generic style"

    class Meta(MetaEnumeration):
        db_table = 'generic_styles'
        verbose_name = _("generic style")

class ContextKeyword(Enumeration):
    "Keyword"

    class Meta(MetaEnumeration):
        db_table = 'context_keywords'
        verbose_name = _("keyword")

class Publisher(Enumeration):
    "Collection publisher"

    class Meta(MetaEnumeration):
        db_table = 'publishers'
        verbose_name = _("publisher")


class PublisherCollection(ModelCore):
    "Collection which belongs to publisher"

    publisher = ForeignKey('Publisher', related_name="publisher_collections", verbose_name=_('publisher'))
    value     = CharField(_('value'), required=True)

    def __unicode__(self):
        return self.value

    class Meta(MetaCore):
        db_table = 'publisher_collections'
        ordering = ['value']


class EthnicGroup(Enumeration):
    "Item ethnic group"

    class Meta(MetaEnumeration):
        db_table = 'ethnic_groups'
        verbose_name = _('population / social group')


class EthnicGroupAlias(ModelCore):
    "Item ethnic group other name"

    ethnic_group = ForeignKey('EthnicGroup', related_name="aliases", verbose_name=_('population / social group'))
    value        = CharField(_('name'), required=True)

    class Meta(MetaCore):
        db_table = 'ethnic_group_aliases'
        unique_together = (('ethnic_group', 'value'),)
        ordering = ['ethnic_group__value']


# Tape formats
class TapeWheelDiameter(Enumeration):
    "Tape wheel diameter (cm)"

    class Meta(MetaEnumeration):
        db_table = 'tape_wheel_diameter'
        verbose_name = _("tape wheel diameter (cm)")

class TapeLength(Enumeration):
    "Tape length (cm)"

    class Meta(MetaEnumeration):
        db_table = 'tape_length'
        verbose_name = _("tape length (cm)")

class TapeWidth(Enumeration):
    "Tape width (inch)"

    class Meta(MetaEnumeration):
        db_table = 'tape_width'
        verbose_name = _("tape width (inch)")

class TapeSpeed(Enumeration):
    "Tape speed (cm/s)"

    class Meta(MetaEnumeration):
        db_table = 'tape_speed'
        verbose_name = _("tape speed (cm/s)")

class TapeVendor(Enumeration):
    "Tape vendor"

    class Meta(MetaEnumeration):
        db_table = 'tape_vendor'
        verbose_name = _("tape brand")


class NumberOfChannels(Enumeration):
    "Number of channels"

    class Meta(MetaEnumeration):
        db_table = 'original_channel_number'
        verbose_name = _("number of channels")


class Organization(Enumeration):
    "Organization"

    class Meta(MetaEnumeration):
        db_table = 'organization'
        verbose_name = _("organization")


class Rights(Enumeration):
    "Archive rights"

    class Meta(MetaEnumeration):
        db_table = 'rights'
        verbose_name = _("rights")


class Topic(Enumeration):
    "Topic, subject of the study, research, etc.."

    class Meta(MetaEnumeration):
        db_table = 'topic'
        verbose_name = _("topic")


class CopyType(Enumeration):
    "Type of the copy"

    class Meta(MetaEnumeration):
        db_table = 'copy_type'
        verbose_name = _("copy type")


class MediaType(Enumeration):
    "Type of the media"

    class Meta(MetaEnumeration):
        db_table = 'media_type'
        verbose_name = _("media type")


class OriginalFormat(Enumeration):
    "Original format"

    class Meta(MetaEnumeration):
        db_table = 'original_format'
        verbose_name = _("original format")


class Status(Enumeration):
    "Resource status"

    class Meta(MetaEnumeration):
        db_table = 'media_status'
        verbose_name = _("collection status")


class IdentifierType(Enumeration):
    "Identifier type"

    class Meta(MetaEnumeration):
        db_table = 'identifier_type'
        verbose_name = _("identifier type")

Module variables

var PUBLIC_ACCESS_CHOICES

var app_name

var code_linesep

var default_decoding

var default_encoding

var eol

var ext

var mime_type

var private_extra_types

var public_extra_types

var strict_code

Classes

class AcquisitionMode

Mode of acquisition of the collection

class AcquisitionMode(Enumeration):
    "Mode of acquisition of the collection"

    class Meta(MetaEnumeration):
        db_table = 'acquisition_modes'
        verbose_name = _("mode of acquisition")

Ancestors (in MRO)

  • AcquisitionMode
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var collections

var compare_function

Inheritance: Enumeration.compare_function

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class AdConversion

Collection digital to analog conversion status

class AdConversion(Enumeration):
    "Collection digital to analog conversion status"

    class Meta(MetaEnumeration):
        db_table = 'ad_conversions'
        verbose_name = _("A/D conversion")

Ancestors (in MRO)

  • AdConversion
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var collections

var compare_function

Inheritance: Enumeration.compare_function

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class ContextKeyword

Keyword

class ContextKeyword(Enumeration):
    "Keyword"

    class Meta(MetaEnumeration):
        db_table = 'context_keywords'
        verbose_name = _("keyword")

Ancestors (in MRO)

  • ContextKeyword
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var compare_function

Inheritance: Enumeration.compare_function

var item_relations

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class CopyType

Type of the copy

class CopyType(Enumeration):
    "Type of the copy"

    class Meta(MetaEnumeration):
        db_table = 'copy_type'
        verbose_name = _("copy type")

Ancestors (in MRO)

  • CopyType
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var collections

var compare_function

Inheritance: Enumeration.compare_function

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class Enumeration

Abstract enumerations base class

class Enumeration(ModelCore):
    "Abstract enumerations base class"

    value = CharField(_('value'), required=True, unique=True)
    notes = TextField(_('notes'))

    def __unicode__(self):
        return self.value

    class Meta(MetaCore):
        abstract = True

Ancestors (in MRO)

  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var ENABLE_M2M_CHECK

var Meta

var compare_function

var notes

var value

Static methods

def get_dom_field_name(

field_name)

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Methods

def __init__(

self, *args, **kwargs)

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class EnumerationProperty

EnumerationProperty(id, enumeration_name, is_hidden, is_admin)

class EnumerationProperty(ModelCore):

    enumeration_name = models.CharField(_('enumeration name'), max_length=255)
    is_hidden = BooleanField(_('is hidden'), default=False)
    is_admin = BooleanField(_('is admin'), default=True)

    class Meta(MetaCore):
        verbose_name = _("enumeration property")
        verbose_name_plural = _("enumeration properties")

    def __unicode__(self):
        return self.enumeration_name

Ancestors (in MRO)

  • EnumerationProperty
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

var Meta

var MultipleObjectsReturned

var compare_function

var enumeration_name

var is_admin

var is_hidden

var objects

Static methods

def get_dom_field_name(

field_name)

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Methods

def __init__(

self, *args, **kwargs)

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class EthnicGroup

Item ethnic group

class EthnicGroup(Enumeration):
    "Item ethnic group"

    class Meta(MetaEnumeration):
        db_table = 'ethnic_groups'
        verbose_name = _('population / social group')

Ancestors (in MRO)

  • EthnicGroup
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var aliases

var compare_function

Inheritance: Enumeration.compare_function

var items

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class EthnicGroupAlias

Item ethnic group other name

class EthnicGroupAlias(ModelCore):
    "Item ethnic group other name"

    ethnic_group = ForeignKey('EthnicGroup', related_name="aliases", verbose_name=_('population / social group'))
    value        = CharField(_('name'), required=True)

    class Meta(MetaCore):
        db_table = 'ethnic_group_aliases'
        unique_together = (('ethnic_group', 'value'),)
        ordering = ['ethnic_group__value']

Ancestors (in MRO)

  • EthnicGroupAlias
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

var Meta

var MultipleObjectsReturned

var compare_function

var ethnic_group

var objects

var value

Static methods

def get_dom_field_name(

field_name)

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Methods

def __init__(

self, *args, **kwargs)

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class GenericStyle

Item generic style

class GenericStyle(Enumeration):
    "Item generic style"

    class Meta(MetaEnumeration):
        db_table = 'generic_styles'
        verbose_name = _("generic style")

Ancestors (in MRO)

  • GenericStyle
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var compare_function

Inheritance: Enumeration.compare_function

var items

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class IdentifierType

Identifier type

class IdentifierType(Enumeration):
    "Identifier type"

    class Meta(MetaEnumeration):
        db_table = 'identifier_type'
        verbose_name = _("identifier type")

Ancestors (in MRO)

  • IdentifierType
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var compare_function

Inheritance: Enumeration.compare_function

var mediacollectionidentifier_set

var mediaitemidentifier_set

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class LegalRight

Collection legal rights

class LegalRight(Enumeration):
    "Collection legal rights"

    class Meta(MetaEnumeration):
        db_table = 'legal_rights'
        verbose_name = _("legal rights")

Ancestors (in MRO)

  • LegalRight
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var collections

var compare_function

Inheritance: Enumeration.compare_function

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class MediaType

Type of the media

class MediaType(Enumeration):
    "Type of the media"

    class Meta(MetaEnumeration):
        db_table = 'media_type'
        verbose_name = _("media type")

Ancestors (in MRO)

  • MediaType
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var collections

var compare_function

Inheritance: Enumeration.compare_function

var items

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class MetaEnumeration

class MetaEnumeration(MetaCore):
    ordering = ['value']

Ancestors (in MRO)

Class variables

var app_label

var ordering

class MetadataAuthor

Collection metadata author

class MetadataAuthor(Enumeration):
    "Collection metadata author"

    class Meta(MetaEnumeration):
        db_table = 'metadata_authors'
        verbose_name = _("record author")

Ancestors (in MRO)

  • MetadataAuthor
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var collections

var compare_function

Inheritance: Enumeration.compare_function

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class MetadataWriter

Collection metadata writer

class MetadataWriter(Enumeration):
    "Collection metadata writer"

    class Meta(MetaEnumeration):
        db_table = 'metadata_writers'
        verbose_name = _("record writer")

Ancestors (in MRO)

  • MetadataWriter
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var collections

var compare_function

Inheritance: Enumeration.compare_function

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class NumberOfChannels

Number of channels

class NumberOfChannels(Enumeration):
    "Number of channels"

    class Meta(MetaEnumeration):
        db_table = 'original_channel_number'
        verbose_name = _("number of channels")

Ancestors (in MRO)

  • NumberOfChannels
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var compare_function

Inheritance: Enumeration.compare_function

var format

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class Organization

Organization

class Organization(Enumeration):
    "Organization"

    class Meta(MetaEnumeration):
        db_table = 'organization'
        verbose_name = _("organization")

Ancestors (in MRO)

  • Organization
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var compare_function

Inheritance: Enumeration.compare_function

var mediaitem_set

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class OriginalFormat

Original format

class OriginalFormat(Enumeration):
    "Original format"

    class Meta(MetaEnumeration):
        db_table = 'original_format'
        verbose_name = _("original format")

Ancestors (in MRO)

  • OriginalFormat
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var collections

var compare_function

Inheritance: Enumeration.compare_function

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class PhysicalFormat

Collection physical format

class PhysicalFormat(Enumeration):
    "Collection physical format"

    class Meta(MetaEnumeration):
        db_table = 'physical_formats'
        verbose_name = _("archive format")

Ancestors (in MRO)

  • PhysicalFormat
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var collections

var compare_function

Inheritance: Enumeration.compare_function

var format

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class Publisher

Collection publisher

class Publisher(Enumeration):
    "Collection publisher"

    class Meta(MetaEnumeration):
        db_table = 'publishers'
        verbose_name = _("publisher")

Ancestors (in MRO)

  • Publisher
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var collections

var compare_function

Inheritance: Enumeration.compare_function

var objects

var publisher_collections

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class PublisherCollection

Collection which belongs to publisher

class PublisherCollection(ModelCore):
    "Collection which belongs to publisher"

    publisher = ForeignKey('Publisher', related_name="publisher_collections", verbose_name=_('publisher'))
    value     = CharField(_('value'), required=True)

    def __unicode__(self):
        return self.value

    class Meta(MetaCore):
        db_table = 'publisher_collections'
        ordering = ['value']

Ancestors (in MRO)

  • PublisherCollection
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

var Meta

var MultipleObjectsReturned

var collections

var compare_function

var objects

var publisher

var value

Static methods

def get_dom_field_name(

field_name)

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Methods

def __init__(

self, *args, **kwargs)

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class PublishingStatus

Collection publishing status

class PublishingStatus(Enumeration):
    "Collection publishing status"

    class Meta(MetaEnumeration):
        db_table = 'publishing_status'
        verbose_name = _("secondary edition")

Ancestors (in MRO)

  • PublishingStatus
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var collections

var compare_function

Inheritance: Enumeration.compare_function

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class RecordingContext

Collection recording context

class RecordingContext(Enumeration):
    "Collection recording context"

    class Meta(MetaEnumeration):
        db_table = 'recording_contexts'
        verbose_name = _("recording context")

Ancestors (in MRO)

  • RecordingContext
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var collections

var compare_function

Inheritance: Enumeration.compare_function

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class Rights

Archive rights

class Rights(Enumeration):
    "Archive rights"

    class Meta(MetaEnumeration):
        db_table = 'rights'
        verbose_name = _("rights")

Ancestors (in MRO)

  • Rights
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var compare_function

Inheritance: Enumeration.compare_function

var mediaitem_set

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class Status

Resource status

class Status(Enumeration):
    "Resource status"

    class Meta(MetaEnumeration):
        db_table = 'media_status'
        verbose_name = _("collection status")

Ancestors (in MRO)

  • Status
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var collections

var compare_function

Inheritance: Enumeration.compare_function

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class TapeLength

Tape length (cm)

class TapeLength(Enumeration):
    "Tape length (cm)"

    class Meta(MetaEnumeration):
        db_table = 'tape_length'
        verbose_name = _("tape length (cm)")

Ancestors (in MRO)

  • TapeLength
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var compare_function

Inheritance: Enumeration.compare_function

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class TapeSpeed

Tape speed (cm/s)

class TapeSpeed(Enumeration):
    "Tape speed (cm/s)"

    class Meta(MetaEnumeration):
        db_table = 'tape_speed'
        verbose_name = _("tape speed (cm/s)")

Ancestors (in MRO)

  • TapeSpeed
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var compare_function

Inheritance: Enumeration.compare_function

var format

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class TapeVendor

Tape vendor

class TapeVendor(Enumeration):
    "Tape vendor"

    class Meta(MetaEnumeration):
        db_table = 'tape_vendor'
        verbose_name = _("tape brand")

Ancestors (in MRO)

  • TapeVendor
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var compare_function

Inheritance: Enumeration.compare_function

var format

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class TapeWheelDiameter

Tape wheel diameter (cm)

class TapeWheelDiameter(Enumeration):
    "Tape wheel diameter (cm)"

    class Meta(MetaEnumeration):
        db_table = 'tape_wheel_diameter'
        verbose_name = _("tape wheel diameter (cm)")

Ancestors (in MRO)

  • TapeWheelDiameter
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var compare_function

Inheritance: Enumeration.compare_function

var format

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class TapeWidth

Tape width (inch)

class TapeWidth(Enumeration):
    "Tape width (inch)"

    class Meta(MetaEnumeration):
        db_table = 'tape_width'
        verbose_name = _("tape width (inch)")

Ancestors (in MRO)

  • TapeWidth
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var compare_function

Inheritance: Enumeration.compare_function

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class Topic

Topic, subject of the study, research, etc..

class Topic(Enumeration):
    "Topic, subject of the study, research, etc.."

    class Meta(MetaEnumeration):
        db_table = 'topic'
        verbose_name = _("topic")

Ancestors (in MRO)

  • Topic
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var compare_function

Inheritance: Enumeration.compare_function

var mediaitem_set

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)

class VernacularStyle

Item vernacular style

class VernacularStyle(Enumeration):
    "Item vernacular style"

    class Meta(MetaEnumeration):
        db_table = 'vernacular_styles'
        verbose_name = _("vernacular style")

Ancestors (in MRO)

  • VernacularStyle
  • Enumeration
  • telemeta.models.core.ModelCore
  • telemeta.models.core.EnhancedModel
  • django.db.models.base.Model
  • dirtyfields.dirtyfields.DirtyFieldsMixin
  • __builtin__.object

Class variables

var DoesNotExist

var ENABLE_M2M_CHECK

Inheritance: Enumeration.ENABLE_M2M_CHECK

var Meta

Inheritance: Enumeration.Meta

var MultipleObjectsReturned

var compare_function

Inheritance: Enumeration.compare_function

var items

var objects

Static methods

def get_dom_field_name(

field_name)

Inheritance: Enumeration.get_dom_field_name

Convert the class name to a DOM element name

@staticmethod
def get_dom_field_name(field_name):
    "Convert the class name to a DOM element name"
    tokens = field_name.split('_')
    name = tokens[0]
    for t in tokens[1:]:
        name += t[0].upper() + t[1:]
    return name

Instance variables

var pk

Inheritance: Enumeration.pk

Methods

def __init__(

self, *args, **kwargs)

Inheritance: Enumeration.__init__

def __init__(self, *args, **kwargs):
    signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
    # Set up the storage for instance state
    self._state = ModelState()
    # There is a rather weird disparity here; if kwargs, it's set, then args
    # overrides it. It should be one or the other; don't duplicate the work
    # The reason for the kwargs check is that standard iterator passes in by
    # args, and instantiation for iteration is 33% faster.
    args_len = len(args)
    if args_len > len(self._meta.concrete_fields):
        # Daft, but matches old exception sans the err msg.
        raise IndexError("Number of args exceeds number of fields")
    if not kwargs:
        fields_iter = iter(self._meta.concrete_fields)
        # The ordering of the zip calls matter - zip throws StopIteration
        # when an iter throws it. So if the first iter throws it, the second
        # is *not* consumed. We rely on this, so don't change the order
        # without changing the logic.
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
    else:
        # Slower, kwargs-ready version.
        fields_iter = iter(self._meta.fields)
        for val, field in zip(args, fields_iter):
            setattr(self, field.attname, val)
            kwargs.pop(field.name, None)
            # Maintain compatibility with existing calls.
            if isinstance(field.rel, ManyToOneRel):
                kwargs.pop(field.attname, None)
    # Now we're left with the unprocessed fields that *must* come from
    # keywords, or default.
    for field in fields_iter:
        is_related_object = False
        # This slightly odd construct is so that we can access any
        # data-descriptor object (DeferredAttribute) without triggering its
        # __get__ method.
        if (field.attname not in kwargs and
                (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
                 or field.column is None)):
            # This field will be populated on request.
            continue
        if kwargs:
            if isinstance(field.rel, ForeignObjectRel):
                try:
                    # Assume object instance was passed in.
                    rel_obj = kwargs.pop(field.name)
                    is_related_object = True
                except KeyError:
                    try:
                        # Object instance wasn't passed in -- must be an ID.
                        val = kwargs.pop(field.attname)
                    except KeyError:
                        val = field.get_default()
                else:
                    # Object instance was passed in. Special case: You can
                    # pass in "None" for related objects if it's allowed.
                    if rel_obj is None and field.null:
                        val = None
            else:
                try:
                    val = kwargs.pop(field.attname)
                except KeyError:
                    # This is done with an exception rather than the
                    # default argument on pop because we don't want
                    # get_default() to be evaluated, and then not used.
                    # Refs #12057.
                    val = field.get_default()
        else:
            val = field.get_default()
        if is_related_object:
            # If we are passed a related instance, set it using the
            # field.name instead of field.attname (e.g. "user" instead of
            # "user_id") so that the object gets properly cached (and type
            # checked) by the RelatedObjectDescriptor.
            setattr(self, field.name, rel_obj)
        else:
            setattr(self, field.attname, val)
    if kwargs:
        for prop in list(kwargs):
            try:
                if isinstance(getattr(self.__class__, prop), property):
                    setattr(self, prop, kwargs.pop(prop))
            except AttributeError:
                pass
        if kwargs:
            raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
    super(Model, self).__init__()
    signals.post_init.send(sender=self.__class__, instance=self)

def clean(

self)

Inheritance: Enumeration.clean

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

def clean(self):
    """
    Hook for doing any extra model-wide validation after clean() has been
    called on every field by self.clean_fields. Any ValidationError raised
    by this method will not be associated with a particular field; it will
    have a special-case association with the field defined by NON_FIELD_ERRORS.
    """
    pass

def clean_fields(

self, exclude=None)

Inheritance: Enumeration.clean_fields

Cleans all fields and raises a ValidationError containing message_dict of all validation errors if any occur.

def clean_fields(self, exclude=None):
    """
    Cleans all fields and raises a ValidationError containing message_dict
    of all validation errors if any occur.
    """
    if exclude is None:
        exclude = []
    errors = {}
    for f in self._meta.fields:
        if f.name in exclude:
            continue
        # Skip validation for empty fields with blank=True. The developer
        # is responsible for making sure they have a valid value.
        raw_value = getattr(self, f.attname)
        if f.blank and raw_value in f.empty_values:
            continue
        try:
            setattr(self, f.attname, f.clean(raw_value, self))
        except ValidationError as e:
            errors[f.name] = e.error_list
    if errors:
        raise ValidationError(errors)

def date_error_message(

self, lookup_type, field, unique_for)

Inheritance: Enumeration.date_error_message

def date_error_message(self, lookup_type, field, unique_for):
    opts = self._meta
    return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
        'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
        'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
        'lookup': lookup_type,
    }

def delete(

self)

Inheritance: Enumeration.delete

def delete(self):
    if not self.pk:
        raise Exception("Can't delete without a primary key")
    self.__class__.objects.filter(pk=self.pk).delete()

def field_label(

cls, field_name=None)

Inheritance: Enumeration.field_label

@classmethod
def field_label(cls, field_name=None):
    if field_name:
        try:
            return cls._meta.get_field(field_name).verbose_name
        except FieldDoesNotExist:
            try:
                return getattr(cls, field_name).verbose_name
            except AttributeError:
                return field_name
    else:
        return cls._meta.verbose_name

def full_clean(

self, exclude=None, validate_unique=True)

Inheritance: Enumeration.full_clean

Calls clean_fields, clean, and validate_unique, on the model, and raises a ValidationError for any errors that occurred.

def full_clean(self, exclude=None, validate_unique=True):
    """
    Calls clean_fields, clean, and validate_unique, on the model,
    and raises a ``ValidationError`` for any errors that occurred.
    """
    errors = {}
    if exclude is None:
        exclude = []
    try:
        self.clean_fields(exclude=exclude)
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Form.clean() is run even if other validation fails, so do the
    # same with Model.clean() for consistency.
    try:
        self.clean()
    except ValidationError as e:
        errors = e.update_error_dict(errors)
    # Run unique checks, but only for fields that passed validation.
    if validate_unique:
        for name in errors.keys():
            if name != NON_FIELD_ERRORS and name not in exclude:
                exclude.append(name)
        try:
            self.validate_unique(exclude=exclude)
        except ValidationError as e:
            errors = e.update_error_dict(errors)
    if errors:
        raise ValidationError(errors)

def get_dirty_fields(

self, check_relationship=False, check_m2m=None, verbose=False)

Inheritance: Enumeration.get_dirty_fields

def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=False):
    if self._state.adding:
        # If the object has not yet been saved in the database, all fields are considered dirty
        # for consistency (see https://github.com/romgar/django-dirtyfields/issues/65 for more details)
        pk_specified = self.pk is not None
        initial_dict = self._as_dict(check_relationship, include_primary_key=pk_specified)
        return initial_dict
    if check_m2m is not None and not self.ENABLE_M2M_CHECK:
        raise ValueError("You can't check m2m fields if ENABLE_M2M_CHECK is set to False")
    modified_fields = compare_states(self._as_dict(check_relationship),
                                     self._original_state,
                                     self.compare_function)
    if check_m2m:
        modified_m2m_fields = compare_states(check_m2m,
                                             self._original_m2m_state,
                                             self.compare_function)
        modified_fields.update(modified_m2m_fields)
    if not verbose:
        # Keeps backward compatibility with previous function return
        modified_fields = {key: value['saved'] for key, value in modified_fields.items()}
    return modified_fields

def get_dom_name(

cls)

Inheritance: Enumeration.get_dom_name

Convert the class name to a DOM element name

@classmethod
def get_dom_name(cls):
    "Convert the class name to a DOM element name"
    clsname = cls.__name__
    return clsname[0].lower() + clsname[1:]

def is_dirty(

self, check_relationship=False, check_m2m=None)

Inheritance: Enumeration.is_dirty

def is_dirty(self, check_relationship=False, check_m2m=None):
    return {} != self.get_dirty_fields(check_relationship=check_relationship,
                                       check_m2m=check_m2m)

def prepare_database_save(

self, unused)

Inheritance: Enumeration.prepare_database_save

def prepare_database_save(self, unused):
    if self.pk is None:
        raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
    return self.pk

def required_fields(

cls)

Inheritance: Enumeration.required_fields

@classmethod
def required_fields(cls):
    required = []
    for field in cls._meta.fields:
        if not field.blank:
            required.append(field)
    return required

def save(

self, force_insert=False, force_update=False, *args, **kwargs)

Inheritance: Enumeration.save

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    required = self.required_fields()
    for field in required:
        if not getattr(self, field.name):
            raise RequiredFieldError(self, field)
    super(ModelCore, self).save(force_insert, force_update, *args, **kwargs)

def save_base(

self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Inheritance: Enumeration.save_base

Handles the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

def save_base(self, raw=False, force_insert=False,
              force_update=False, using=None, update_fields=None):
    """
    Handles the parts of saving which should be done only once per save,
    yet need to be done in raw saves, too. This includes some sanity
    checks and signal sending.
    The 'raw' argument is telling save_base not to save any parent
    models and not to do any changes to the values before save. This
    is used by fixture loading.
    """
    using = using or router.db_for_write(self.__class__, instance=self)
    assert not (force_insert and (force_update or update_fields))
    assert update_fields is None or len(update_fields) > 0
    cls = origin = self.__class__
    # Skip proxies, but keep the origin as the proxy model.
    if cls._meta.proxy:
        cls = cls._meta.concrete_model
    meta = cls._meta
    if not meta.auto_created:
        signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
                              update_fields=update_fields)
    with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
        if not raw:
            self._save_parents(cls, using, update_fields)
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    # Store the database on which the object was saved
    self._state.db = using
    # Once saved, this is no longer a to-be-added instance.
    self._state.adding = False
    # Signal that the save is complete
    if not meta.auto_created:
        signals.post_save.send(sender=origin, instance=self, created=(not updated),
                               update_fields=update_fields, raw=raw, using=using)

def save_dirty_fields(

self)

Inheritance: Enumeration.save_dirty_fields

def save_dirty_fields(self):
    dirty_fields = self.get_dirty_fields(check_relationship=True)
    save_specific_fields(self, dirty_fields)

def serializable_value(

self, field_name)

Inheritance: Enumeration.serializable_value

Returns the value of the field name for this instance. If the field is a foreign key, returns the id value, instead of the object. If there's no Field object with this name on the model, the model attribute's value is returned directly.

Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

def serializable_value(self, field_name):
    """
    Returns the value of the field name for this instance. If the field is
    a foreign key, returns the id value, instead of the object. If there's
    no Field object with this name on the model, the model attribute's
    value is returned directly.
    Used to serialize a field's value (in the serializer, or form output,
    for example). Normally, you would just access the attribute directly
    and not use this method.
    """
    try:
        field = self._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return getattr(self, field_name)
    return getattr(self, field.attname)

def to_dict(

self)

Inheritance: Enumeration.to_dict

Return model fields as a dict of name/value pairs

def to_dict(self):
    "Return model fields as a dict of name/value pairs"
    fields_dict = {}
    for field in self._meta.fields:
        fields_dict[field.name] = getattr(self, field.name)
    return fields_dict

def to_dom(

self)

Inheritance: Enumeration.to_dom

Return the DOM representation of this media object

def to_dom(self):
    "Return the DOM representation of this media object"
    impl = getDOMImplementation()
    root = self.get_dom_name()
    doc = impl.createDocument(None, root, None)
    top = doc.documentElement
    top.setAttribute("id", str(self.pk))
    fields = self.to_dict()
    for name, value in fields.iteritems():
        element = doc.createElement(self.get_dom_field_name(name))
        if isinstance(value, EnhancedModel):
            element.setAttribute('key', str(value.pk))
        value = unicode(value)
        element.appendChild(doc.createTextNode(value))
        top.appendChild(element)
    return doc

def to_list(

self)

Inheritance: Enumeration.to_list

Return model fields as a list

def to_list(self):
    "Return model fields as a list"
    fields_list = []
    for field in self._meta.fields:
        fields_list.append({'name': field.name, 'value': unicode(getattr(self, field.name))})
    return fields_list

def unique_error_message(

self, model_class, unique_check)

Inheritance: Enumeration.unique_error_message

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)
    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field = opts.get_field(field_name)
        field_label = capfirst(field.verbose_name)
        # Insert the error into the error dict, very sneaky
        return field.error_messages['unique'] % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_label)
        }
    # unique_together
    else:
        field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
        field_labels = get_text_list(field_labels, _('and'))
        return _("%(model_name)s with this %(field_label)s already exists.") % {
            'model_name': six.text_type(model_name),
            'field_label': six.text_type(field_labels)
        }

def validate_unique(

self, exclude=None)

Inheritance: Enumeration.validate_unique

Checks unique constraints on the model and raises ValidationError if any failed.

def validate_unique(self, exclude=None):
    """
    Checks unique constraints on the model and raises ``ValidationError``
    if any failed.
    """
    unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
    errors = self._perform_unique_checks(unique_checks)
    date_errors = self._perform_date_checks(date_checks)
    for k, v in date_errors.items():
        errors.setdefault(k, []).extend(v)
    if errors:
        raise ValidationError(errors)