Ejemplo n.º 1
0
    from taggit_autocomplete_modified.managers import TaggableManagerAutocomplete as BaseTaggableManager
elif is_installed('taggit'):
    from taggit.managers import TaggableManager as BaseTaggableManager
else:
    BaseTaggableManager = None

# Make sure the 'tags' field is ignored by old versions of South
try:
    from south.modelsinspector import add_ignored_fields
except ImportError:
    pass
else:
    # South should ignore the tags field as it's a RelatedField.
    add_ignored_fields((
        "^taggit\.managers\.TaggableManager",
        "^taggit_selectize\.managers\.TaggableManager",
        "^taggit_autosuggest\.managers\.TaggableManager",
        "^taggit_autocomplete_modified\.managers\.TaggableManagerAutocomplete",
    ))

if BaseTaggableManager is not None:
    # Make sure the migrations have one consistent path to import from
    class TaggableManager(BaseTaggableManager):
        pass
else:

    class TaggableManager(Field):
        def __bool__(self):
            return False  # partial compatibility with old code.

        def __nonzero__(self):
            return False  # Python 2
from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _

from taggit.forms import TagField
from taggit.managers import TaggableManager as BaseTaggableManager

from widgets import TagAutocomplete


class TaggableManager(BaseTaggableManager):
    def formfield(self, form_class=TagField, **kwargs):
        defaults = {
            "label": capfirst(self.verbose_name),
            "help_text": _("A comma-separated list of tags."),
            "required": not self.blank,
        }
        defaults.update(kwargs)

        defaults['widget'] = TagAutocomplete

        return form_class(**defaults)

# South introspection rule
try:
    from south.modelsinspector import add_ignored_fields
    add_ignored_fields(["^taggit_autocomplete\.managers"])
except ImportError:
    pass
"""
South introspection rules for django-objectpermissions
"""

from django.conf import settings
from south.modelsinspector import add_ignored_fields

if 'objectpermissions' in settings.INSTALLED_APPS:
    try:
        from objectpermissions.models import UserPermissionRelation, GroupPermissionRelation
    except ImportError:
        pass
    else:
        add_ignored_fields(["^objectpermissions\.models\.UserPermissionRelation",
                            "^objectpermissions\.models\.GroupPermissionRelation"])

Ejemplo n.º 4
0
from django.db import models
from model_utils.models import TimeStampedModel
from model_utils.managers import QueryManager

from djorm_pgfulltext.models import SearchManager
from djorm_pgfulltext.fields import VectorField
from taggit_autosuggest_select2.managers import TaggableManager
from tinymce import models as tinymce_models
from south.modelsinspector import add_ignored_fields

add_ignored_fields(["^taggit_autosuggest_select2\.managers"])

class Link(TimeStampedModel):
    url = models.CharField("URL", max_length=1024, unique=True)
    read = models.DateTimeField("Date read", null=True, blank=True)
    summary = tinymce_models.HTMLField(blank=True)
    title = models.CharField("Title", max_length=1024, blank=True)
    search_index = VectorField()

    objects = SearchManager(
        fields = ('title', 'summary'),
        config = 'pg_catalog.english',   # this is default
        search_field = 'search_index',   # this is default
        auto_update_search_field = False # we do it using a trigger
    )

    objects_read = QueryManager(read__isnull=False).order_by('created')
    objects_unread = QueryManager(read__isnull=True).order_by('created')

    tags = TaggableManager(blank=True)
Ejemplo n.º 5
0
import re

from django.db.models import CharField
from django.forms.fields import RegexField

from widgets import ColorFieldWidget

RGB_REGEX = re.compile('^#?([0-F]{3}|[0-F]{6})$', re.IGNORECASE)

class RGBColorField(CharField):
    
    widget = ColorFieldWidget
    
    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 7
        super(RGBColorField, self).__init__(*args, **kwargs)
        
    def formfield(self, **kwargs):
        kwargs.update({
                       'form_class': RegexField,
                       'widget': self.widget,
                       'regex': RGB_REGEX
                       })
        return super(RGBColorField, self).formfield(**kwargs)

try:
    from south.modelsinspector import add_ignored_fields
    add_ignored_fields(['^colorful\.fields'])
except ImportError:
    pass
Ejemplo n.º 6
0
# coding: utf-8

from django.db import models
from django.utils.translation import ugettext_lazy as _

from django_extensions.db import fields

from datetime import datetime
from gpbweb.postgres_fts import models as fts_models

from south.modelsinspector import add_ignored_fields

add_ignored_fields(["^gpbweb\.postgres_fts\.models\.VectorField",])


class ProveedorManager(models.Manager):

    def por_compras(self, **filter_args):

        filter_args['compra__fecha__gte'] = filter_args.get('compra__fecha__gte', datetime(datetime.now().year, datetime.now().month, 1))
        filter_args['compra__fecha__lte'] = filter_args.get('compra__fecha__lte', datetime.now())

        return self.select_related('compra_set') \
            .filter(**filter_args) \
            .annotate(total_compras=models.Sum('compra__importe')) \
            .order_by('-total_compras')

class Proveedor(models.Model):

    objects = ProveedorManager()
Ejemplo n.º 7
0
class AbstractTranslatableEntry(
    AbstractTranslatableEntryBase, ContentsEntryMixin, CommentsEntryMixin, CategoriesEntryMixin, TagsEntryMixin
):
    """
    The default entry model for translated blog posts, as abstract model.
    """

    class Meta:
        abstract = True


class AbstractTranslatedFieldsEntry(AbstractTranslatedFieldsEntryBase, ExcerptEntryMixin, SeoEntryMixin):
    """
    The default translated fields model for blog posts, as abstract model.
    """

    class Meta:
        abstract = True


# Make sure the 'tags' field is ignored by South
try:
    from south.modelsinspector import add_ignored_fields
except ImportError:
    pass
else:
    # South should ignore the tags field as it's a RelatedField.
    add_ignored_fields(
        ("^taggit\.managers\.TaggableManager", "^taggit_autocomplete_modified\.managers\.TaggableManagerAutocomplete")
    )
Ejemplo n.º 8
0
    ('VC', _('St. Vincent & the Grenadines')),
    ('VE', _('Venezuela')),
    ('VG', _('British Virgin Islands')),
    ('VI', _('United States Virgin Islands')),
    ('VN', _('Viet Nam')),
    ('VU', _('Vanuatu')),
    ('WF', _('Wallis & Futuna Islands')),
    ('WS', _('Samoa')),
    ('YE', _('Yemen')),
    ('YT', _('Mayotte')),
    ('YU', _('Yugoslavia')),
    ('ZA', _('South Africa')),
    ('ZM', _('Zambia')),
    ('ZR', _('Zaire')),
    ('ZW', _('Zimbabwe')),
    ('ZZ', _('Unknown or unspecified country')),
)

class CountryField(models.CharField):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault('max_length', 2)
        kwargs.setdefault('choices', COUNTRIES)

        super(CountryField, self).__init__(*args, **kwargs)

    def get_internal_type(self):
        return "CharField"

from south.modelsinspector import add_ignored_fields 
add_ignored_fields(["^webEval\.web_eval__core\.fields.CountryField"]) 
Ejemplo n.º 9
0
from django.core.urlresolvers import reverse

# 3rdparty imports
import Image
from uuslug import uuslug
from tinymce.models import HTMLField
from djangoratings.fields import RatingField, AnonymousRatingField
from taggit_autocomplete_modified.managers import TaggableManagerAutocomplete as TaggableManager
# app imports
from declarations import *
from south.modelsinspector import add_ignored_fields
from constance import config
import watson

## South
add_ignored_fields(["^taggit\.managers"])
add_ignored_fields(["^taggit_autocomplete_modified\.managers"])
add_ignored_fields(["^taggit_autocomplete/.managers"])


class BookNotAvailableError(Exception):
    pass


class Locations(models.Model):
    title = models.CharField(max_length=255, verbose_name=u'Τοποθεσία')

    class Meta:
        verbose_name = u"Τοποθεσία"
        verbose_name_plural = u"Τοποθεσίες"
"""
South introspection rules for django-objectpermissions
"""

from django.conf import settings
from south.modelsinspector import add_ignored_fields

if 'objectpermissions' in settings.INSTALLED_APPS:
    try:
        from objectpermissions.models import UserPermissionRelation, GroupPermissionRelation
    except ImportError:
        pass
    else:
        add_ignored_fields([
            "^objectpermissions\.models\.UserPermissionRelation",
            "^objectpermissions\.models\.GroupPermissionRelation"
        ])
Ejemplo n.º 11
0
            assigned to the correct instance of the object in memory.

            Keyword arguments:
            content_object -- the object that the property should be added to,
                              which must inherit from BaseModel.
            """

            kwargs[self.content_type_field_name] = self.content_type
            kwargs[self.object_id_field_name] = self.pk_val
            db = router.db_for_write(self.model, instance=self.instance)
            obj = super(
                BaseGenericRelatedObjectManager,
                self
            ).using(db).create(**kwargs)

            if content_object and hasattr(content_object, 'set_attribute'):
                content_object.set_attribute(obj.name, obj.value)

            return obj
        create.alters_data = True

    return BaseGenericRelatedObjectManager


try:
    # We need this to support South properly.
    from south.modelsinspector import add_ignored_fields
    add_ignored_fields(["^django_base_model\.generic\.BaseGenericRelation"])
except:
    pass
Ejemplo n.º 12
0
"""
South introspection rule for TimeZoneField

Source: http://djangosnippets.org/snippets/2395/
"""
from timezones.fields import TimeZoneField
from timezones.zones import PRETTY_TIMEZONE_CHOICES
from south.modelsinspector import add_introspection_rules, add_ignored_fields
from django.conf import settings


add_introspection_rules(rules=[
        ((TimeZoneField,),
        [],
        {
            "default": ["default", {"default": settings.TIME_ZONE}],
            "choices": ["choices", {"default": PRETTY_TIMEZONE_CHOICES}],
            "max_length": ["max_length", {"default":getattr(settings,
                "MAX_TIMEZONE_LENGTH", 100)}],
        }
        )
    ],
    patterns=['timezones\.fields', ])

add_ignored_fields(["^pyconde\.tagging"])
Ejemplo n.º 13
0
__author__ = 'aldaran'

from compositekey.db.models import *

try:
    from south.modelsinspector import add_ignored_fields

    add_ignored_fields(
        ["^compositekey\.db\.models\.fields\.multiplekey\.MultiFieldPK$"])
except ImportError:
    pass
Ejemplo n.º 14
0
    @classmethod
    def get_cache_name(cls):
        return '_mediacat_crop_cache'

    def get_attname(self):
        return self.name

    def get_attname_column(self):
        attname = self.get_attname()
        return attname, None

    def formfield(self, **kwargs):
        widget = kwargs.pop('widget', MediaInput())

        defaults = {
            'crops': self.crops,
            'form_class': MediaFormField,
            'field': self,
        }
        defaults.update(kwargs)
        defaults['widget'] = widget
        return super(MediaField, self).formfield(**defaults)


# south compatibility, ignore virtual fields
try:
    from south.modelsinspector import add_ignored_fields
    add_ignored_fields(["^mediacat\.fields\.MediaField"])
except ImportError:
    pass
Ejemplo n.º 15
0
# This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and
# is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012)

import django
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.generic import GenericForeignKey
from django.db import models, IntegrityError, transaction
from django.template.defaultfilters import slugify as default_slugify
from django.utils.translation import ugettext_lazy as _, ugettext

from south.modelsinspector import add_ignored_fields

add_ignored_fields(["^geoevents\.taggit\.managers"])


class TagBase(models.Model):
    name = models.CharField(verbose_name=_('Name'), max_length=100)
    slug = models.SlugField(verbose_name=_('Slug'),
                            unique=True,
                            max_length=100)

    def __unicode__(self):
        return self.name

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        if not self.pk and not self.slug:
            self.slug = self.slugify(self.name)
            if django.VERSION >= (1, 2):
Ejemplo n.º 16
0
from django.contrib.contenttypes.generic import GenericRelation
from south.modelsinspector import add_ignored_fields
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured


# Trick rest_framework into serializing these relationships
class SerializableGenericRelation(GenericRelation):
    def __init__(self, *args, **kwargs):
        super(SerializableGenericRelation, self).__init__(*args, **kwargs)
        self.serialize = True

add_ignored_fields(["^wq.db.patterns.base.SerializableGenericRelation"])


# Utility for determining whether models have been swapped
class Swapper(object):
    def swappable_setting(self, app_label, model):
        if app_label == 'auth' and model == 'User':
            return 'AUTH_USER_MODEL'
        return 'WQ_%s_MODEL' % model.upper()

    def is_swapped(self, app_label, model):
        default_model = "%s.%s" % (app_label, model)
        setting = self.swappable_setting(app_label, model)
        value = getattr(settings, setting, default_model)
        if value != default_model:
            return value
        else:
            return False
Ejemplo n.º 17
0
    We use it to reset the name of the socialaccount provider in
    the user's session to one that he also has.
    """
    user = socialaccount.user
    try:
        all_socialaccounts = user.socialaccount_set.all()
        next_socialaccount = all_socialaccounts[0]
        request.session['sociallogin_provider'] = next_socialaccount.provider
        request.session.modified = True
    except (ObjectDoesNotExist, IndexError):
        pass


# from https://github.com/brosner/django-timezones/pull/13
try:
    from south.modelsinspector import (add_introspection_rules,
                                       add_ignored_fields)
    add_ignored_fields(["^taggit\.managers"])
    add_introspection_rules(rules=[(
            (TimeZoneField,),   # Class(es) these apply to
            [],                 # Positional arguments (not used)
            {                   # Keyword argument
            "max_length": ["max_length", {"default": MAX_TIMEZONE_LENGTH}],
            }
            )],
        patterns=['timezones\.fields\.'])
    add_introspection_rules([], ['sumo.models.LocaleField'])
except ImportError:
    pass
Ejemplo n.º 18
0
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager, SiteProfileNotAvailable
from django.core import validators
from django.db import models
from core.thumbs import ImageWithThumbsField
from core.taggit.managers import TaggableManager
from cache_tools.models import KeyableModel
from cache_tools.tools import expire_page
from django.core.urlresolvers import reverse
from django.core.exceptions import ImproperlyConfigured
from core.helpers import format_phone_number
import datetime
import re
from django.utils import timezone
from south.modelsinspector import add_ignored_fields

add_ignored_fields(["^core\.taggit\.managers\.TaggableManager"])


class App(models.Model):
    title = models.CharField(max_length=255)
    stub = models.CharField(max_length=32)
    description = models.CharField(max_length=255)
    path = models.CharField(max_length=32)
    icon_file = ImageWithThumbsField(upload_to='app_icons',
                                     sizes=(
                                         (300, 300), (200, 200), (100, 100)),
                                     default='app_icons/default.jpg',
                                     null=True,
                                     blank=True)

    def __unicode__(self):
Ejemplo n.º 19
0
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext
#from mptt.models import MPTTModel, TreeForeignKey
from django.utils.safestring import mark_safe
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.generic import GenericForeignKey
from coop_tag.settings import get_class, TAGGER_FKEY_NAME
from django.conf import settings
from django.db import router
import re

import slugify

try:
    from south.modelsinspector import add_ignored_fields
    add_ignored_fields(["^coop_tag\.managers"])
except ImportError:
    pass  # without south this can fail silently


class TagBase(models.Model):
    name = models.CharField(verbose_name=_('Name'), max_length=100)
    slug = models.SlugField(verbose_name=_('Slug'), unique=True, max_length=100)
    # parent = TreeForeignKey('self', null=True, blank=True, related_name='children')

    def __unicode__(self):
        return self.name

    # class MPTTMeta:
    #     order_insertion_by = ['name']
Ejemplo n.º 20
0
from tags.forms import TagField


class BigVocabTaggableManager(TaggableManager):
    """TaggableManager for choosing among a predetermined set of tags

    Taggit's seems hard-coupled to taggit's own plain-text-input widget.

    """
    def formfield(self, form_class=TagField, **kwargs):
        """Swap in our custom TagField."""
        return super(BigVocabTaggableManager,
                     self).formfield(form_class, **kwargs)


class BigVocabTaggableMixin(models.Model):
    """Mixin for taggable models that still allows a caching manager to be the
    default manager

    Mix this in after [your caching] ModelBase.

    """
    tags = BigVocabTaggableManager()

    class Meta:
        abstract = True


add_ignored_fields(["tags\.models\.BigVocabTaggableManager"])
from django.utils.translation import ugettext_lazy as _

from taggit.forms import TagField
from taggit.managers import TaggableManager as BaseTaggableManager

from taggit_autocomplete.widgets import TagAutocomplete


class TaggableManager(BaseTaggableManager):
    def formfield(self, form_class=TagField, **kwargs):
        defaults = {
            "label": _("Tags"),
            "help_text": _("A comma-separated list of tags."),
            "required": not self.blank,
        }
        defaults.update(kwargs)

        defaults['widget'] = TagAutocomplete

        return form_class(**defaults)


# South introspection rule
try:
    from south.modelsinspector import add_ignored_fields
    add_ignored_fields(["^taggit_autocomplete\.managers"])
except ImportError:
    pass
Ejemplo n.º 22
0
    Taggit's seems hard-coupled to taggit's own plain-text-input widget.

    """
    def formfield(self, form_class=TagField, **kwargs):
        """Swap in our custom TagField."""
        return super(BigVocabTaggableManager, self).formfield(form_class,
                                                              **kwargs)


# taggit adds a "tags" property which isn't a field, but South can't
# tell the difference. So we tell south to ignore everything in this
# module.
#
# Note: If we end up adding models to this module, then we'll need to
# rethink this.
from south.modelsinspector import add_ignored_fields
add_ignored_fields(["^kitsune\.tags\.models"])


class BigVocabTaggableMixin(models.Model):
    """Mixin for taggable models that still allows a caching manager to be the
    default manager

    Mix this in after [your caching] ModelBase.

    """
    tags = BigVocabTaggableManager()

    class Meta:
        abstract = True
Ejemplo n.º 23
0
elif is_installed('taggit'):
    from taggit.managers import TaggableManager as BaseTaggableManager
else:
    BaseTaggableManager = None


# Make sure the 'tags' field is ignored by old versions of South
try:
    from south.modelsinspector import add_ignored_fields
except ImportError:
    pass
else:
    # South should ignore the tags field as it's a RelatedField.
    add_ignored_fields((
        "^taggit\.managers\.TaggableManager",
        "^taggit_selectize\.managers\.TaggableManager",
        "^taggit_autosuggest\.managers\.TaggableManager",
        "^taggit_autocomplete_modified\.managers\.TaggableManagerAutocomplete",
    ))


if BaseTaggableManager is not None:
    # Make sure the migrations have one consistent path to import from
    class TaggableManager(BaseTaggableManager):
        pass
else:
    class TaggableManager(Field):
        def __bool__(self):
            return False  # partial compatibility with old code.

        def __nonzero__(self):
            return False  # Python 2
Ejemplo n.º 24
0
import decimal
from datetime import datetime

from django.db import models, connection, transaction
from django.utils.translation import ugettext_lazy as _

from django_extensions.db import fields

from pergaminoweb.postgres_fts import models as fts_models

from south.modelsinspector import add_ignored_fields

# add_ignored_fields(["^pergaminoweb\.postgres_fts\.models\.VectorField",
#                     "^django_extensions\.db\.fields\.AutoSlugField",
#                     "^django_extensions\.db\.fields\.CreationDateTimeField"])
add_ignored_fields(["^pergaminoweb\.postgres_fts\.models\.VectorField"])


##### BEGIN Monkeypatch de AutoSlugField y CreationDateTimeField
# backporteado de aca: https://raw.github.com/django-extensions/django-extensions/master/django_extensions/db/fields/__init__.py
def autoslug_south_field_triple(self):
    "Returns a suitable description of this field for South."
    # We'll just introspect the _actual_ field.
    from south.modelsinspector import introspector
    field_class = "django.db.models.fields.SlugField"
    args, kwargs = introspector(self)
    # That's our definition!
    return (field_class, args, kwargs)

def creationdatetime_south_field_triple(self):
    "Returns a suitable description of this field for South."
Ejemplo n.º 25
0
class CommentsRelation(GenericRelation):
    """
    A :class:`~django.contrib.contenttypes.generic.GenericRelation` which can be applied to a parent model that
    is expected to have comments. For example:

    .. code-block:: python

        class Article(models.Model):
            comments_set = CommentsRelation()
    """
    def __init__(self, *args, **kwargs):
        super(CommentsRelation, self).__init__(
            to=get_comments_model(),
            content_type_field='content_type',
            object_id_field='object_pk',
            **kwargs
        )


try:
    from south.modelsinspector import add_ignored_fields
except ImportError:
    pass
else:
    # South 0.7.x ignores GenericRelation fields but doesn't ignore subclasses.
    # Taking the same fix as applied in http://south.aeracode.org/ticket/414
    _name_re = "^" + __name__.replace(".", "\.")
    add_ignored_fields((
        _name_re + "\.CommentsRelation",
    ))
Ejemplo n.º 26
0
    Taggit's seems hard-coupled to taggit's own plain-text-input widget.

    """
    def formfield(self, form_class=TagField, **kwargs):
        """Swap in our custom TagField."""
        return super(BigVocabTaggableManager,
                     self).formfield(form_class, **kwargs)


# taggit adds a "tags" property which isn't a field, but South can't
# tell the difference. So we tell south to ignore everything in this
# module.
#
# Note: If we end up adding models to this module, then we'll need to
# rethink this.
add_ignored_fields(["^kitsune\.tags\.models"])


class BigVocabTaggableMixin(models.Model):
    """Mixin for taggable models that still allows a caching manager to be the
    default manager

    Mix this in after [your caching] ModelBase.

    """
    tags = BigVocabTaggableManager()

    class Meta:
        abstract = True
Ejemplo n.º 27
0
class Act(NewsTargetMixin, MonitorizedItem, TimeStampedModel):
    """
    This is the base class for all the different act types: it contains the common fields for
    deliberations, interrogations, interpellations, motions, agendas and emendations.
  
    it is a ``TimeStampedModel``, so it tracks creation and modification timestamps for each record.

    The ``related_news`` attribute can be used  to fetch news related to a given act.

    Inheritance is done through multi-table inheritance, since browsing the whole set of acts may be useful.
    The default manager is the ``InheritanceManager`` (from package `django-model-utils`_),
    providing the ``select_subclasses()`` method, which allows the retrieval of concrete subclasses' instances, 
    if needed.


    .. _django-model-utils: https://bitbucket.org/carljm/django-model-utils/src

    """
    # added to avoid problems with South migrations
    add_ignored_fields(["^open_municipio\.taxonomy\.managers"])

    idnum = models.CharField(
        max_length=64,
        blank=True,
        help_text=
        _("A string representing the identification or sequence number for this act, used internally by the municipality's administration."
          ))
    title = models.CharField(_('title'), max_length=1024, blank=True)
    adj_title = models.CharField(
        _('adjoint title'),
        max_length=1024,
        blank=True,
        help_text=
        _("An adjoint title, added to further explain an otherwise cryptic title"
          ))
    presentation_date = models.DateField(
        _('presentation date'),
        null=True,
        help_text=_("Date of presentation, as stated in the act"))
    description = models.TextField(_('description'), blank=True)
    text = models.TextField(_('text'), blank=True)
    presenter_set = models.ManyToManyField(InstitutionCharge,
                                           blank=True,
                                           null=True,
                                           through='ActSupport',
                                           related_name='presented_act_set',
                                           verbose_name=_('presenters'))
    recipient_set = models.ManyToManyField(InstitutionCharge,
                                           blank=True,
                                           null=True,
                                           related_name='received_act_set',
                                           verbose_name=_('recipients'))
    emitting_institution = models.ForeignKey(
        Institution,
        related_name='emitted_act_set',
        verbose_name=_('emitting institution'))
    category_set = models.ManyToManyField('taxonomy.Category',
                                          verbose_name=_('categories'),
                                          blank=True,
                                          null=True)
    location_set = models.ManyToManyField(
        'locations.Location',
        through='locations.TaggedActByLocation',
        verbose_name=_('locations'),
        blank=True,
        null=True)
    status_is_final = models.BooleanField(default=False)
    is_key = models.BooleanField(
        default=False,
        help_text=_("Specify whether this act should be featured"))

    objects = InheritanceManager()
    # use this manager to retrieve only key acts
    featured = QueryManager(is_key=True).order_by('-presentation_date')

    tag_set = TopicableManager(through='taxonomy.TaggedAct', blank=True)

    # use this manager to retrieve the QuerySet of ``Monitoring`` instances
    # having as their ``content_object`` this act
    monitoring_set = generic.GenericRelation(Monitoring,
                                             object_id_field='object_pk')

    def __unicode__(self):
        rv = u'%s' % (self.title, )
        if self.idnum:
            rv = u'%s - %s' % (self.idnum, rv)
        if self.adj_title:
            rv = u'%s (%s)' % (rv, self.adj_title)
        return rv

    def downcast(self):
        """
        Returns the "downcasted"[*]_ version of this model instance.
        

        .. [*]: In a multi-table model inheritance scenario, the term "downcasting"
                refers to the process of retrieving the child model instance given the 
                parent model instance.
        """
        # FIXME: this check is redundant, IMO (@seldon)
        # if this method is called from a "concrete" instance
        # the lookup machinery either will return the instance itself
        # or a downcasted version of it (if any), which seems to me
        # the right behaviour for a ``downcast()`` method.
        if hasattr(
                self,
                'act_ptr'):  # method is being called from a subclass' instance
            return self
        cls = self.__class__  # ``self`` is an instance of the parent model
        for r in cls._meta.get_all_related_objects():
            if not issubclass(r.model, cls) or\
               not isinstance(r.field, models.OneToOneField):
                continue
            try:
                return getattr(self, r.get_accessor_name())
            except models.ObjectDoesNotExist:
                continue

    @property
    def attachments(self):
        return self.attachment_set.all()

    @property
    def transitions(self):
        return self.transition_set.all()

    @property
    def presenters(self):
        return self.presenter_set.all()

    @property
    def first_presenters(self):
        return self.presenter_set.filter(
            actsupport__support_date=self.presentation_date)

    @property
    def recipients(self):
        return self.recipient_set.all()

    @property
    def first_signers(self):
        # FIXME: resolve asymmetry between this query and that for ``co_signers`` property
        return InstitutionCharge.objects.filter(
            actsupport__act__id=self.pk,
            actsupport__support_type=ActSupport.SUPPORT_TYPE.first_signer)

    @property
    def co_signers(self):
        # FIXME: resolve asymmetry between this query and that for ``first_signers`` property
        return self.presenter_set.filter(
            actsupport__support_type=ActSupport.SUPPORT_TYPE.co_signer)

    @property
    def emendations(self):
        return self.emendation_set.all()

    @property
    def tags(self):
        # FIXME: cleanup needed, here!
        return list(
            set([topic.tag for topic in self.topics if topic.tag is not None]))

    @property
    def categories(self):
        # FIXME: cleanup needed, here!
        return list(
            set([
                topic.category for topic in self.topics
                if topic.category is not None
            ]))

    @property
    def topics(self):
        return self.tag_set.topics()

    @property
    def locations(self):
        return self.location_set.all()

    @property
    def act_descriptors(self):
        """
        Return the QuerySet of all those users which modified this act's description.
        """
        return self.actdescriptor_set.all()

    @property
    def is_key_yesno(self):
        # FIXME: this property should be implemented as a template filter,
        # since it only contains presentational logic
        if self.is_key:
            return _('yes')
        else:
            return _('no')

    def status(self):
        """
        Return the current status for the downcasted version of this act instance.
        
        .. note:: 

            It seems that this method cannot be made into a property,
            since doing that would trigger an ``AttributeError: can't set attribute`` exception 
            during Django initialization. 

        """
        return self.downcast().status

    def get_transitions_groups(self):
        """
        Retrieve a list of transitions grouped by status.
        """
        # TODO: review implementation
        groups = {}
        this = self.downcast()
        if not hasattr(this, 'STATUS'):
            return groups
        # initialize all status with an empty list of transitions
        for status in this.STATUS:
            groups[status[0]] = []
        # fill groups with ordered transitions
        for transition in this.transitions.order_by('-transition_date'):
            if groups.has_key(transition.final_status):
                groups.get(transition.final_status).append(transition)
        return groups

    def is_final_status(self, status=None):
        """
        WRITEME
        """
        # TODO: review implementation
        this = self.downcast()
        if status is None:
            status = this.status

        if not hasattr(this, 'FINAL_STATUSES'):
            return False

        for final_status in this.FINAL_STATUSES:
            if status == final_status[0]:
                return True
        return False

    def get_last_transition(self):
        """
        WRITEME
        """
        # TODO: review implementation
        if self.transitions:
            # FIXME: this assume that transitions are ordered by date
            return list(self.transitions)[-1]
        # FIXME: this method returns different kind of objects (list or boolean)
        # under different conditions: this is not an ideal API!
        # A better approach would be to return ``None`` or raise an exception
        # if no transitions exist for this act
        return False

    def get_absolute_url(self):
        return self.downcast().get_absolute_url()

    def get_status_display(self):
        """
        WRITEME
        """
        return self.downcast().get_status_display()

    def get_type_name(self):
        """
        WRITEME
        """
        if self.downcast():
            return self.downcast()._meta.verbose_name
        else:
            return None
Ejemplo n.º 28
0
"""
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from collab.settings import INSTALLED_APPS
from django.db import models
from core.thumbs import ImageWithThumbsField
from core.taggit.managers import TaggableManager
from cache_tools.models import KeyableModel
from cache_tools.tools import expire_page
from django.core.urlresolvers import reverse
from core.helpers import format_phone_number
import datetime
from django.utils import timezone
from south.modelsinspector import add_ignored_fields

add_ignored_fields(["^core\.taggit\.managers\.TaggableManager"])


class App(models.Model):
    title = models.CharField(max_length=255)
    stub = models.CharField(max_length=32)
    description = models.CharField(max_length=255)
    path = models.CharField(max_length=32)
    icon_file = ImageWithThumbsField(upload_to='app_icons',
                                     sizes=(
                                         (300, 300), (200, 200), (100, 100)),
                                     default='app_icons/default.jpg',
                                     null=True,
                                     blank=True)

    def __unicode__(self):
Ejemplo n.º 29
0
__author__ = 'aldaran'

from compositekey.db.models import *


try:
    from south.modelsinspector import add_ignored_fields

    add_ignored_fields(["^compositekey\.db\.models\.fields\.multiplekey\.MultiFieldPK$"])
except ImportError:
    pass


Ejemplo n.º 30
0
try:
    from south.modelsinspector import add_ignored_fields
    add_ignored_fields(["^taggit_autosuggest_select2\.managers"])
except ImportError:
    pass  # without south this can fail silently
 
Ejemplo n.º 31
0
    Invoked just after a user successfully removed a social account

    We use it to reset the name of the socialaccount provider in
    the user's session to one that he also has.
    """
    user = socialaccount.user
    try:
        all_socialaccounts = user.socialaccount_set.all()
        next_socialaccount = all_socialaccounts[0]
        request.session['sociallogin_provider'] = next_socialaccount.provider
        request.session.modified = True
    except (ObjectDoesNotExist, IndexError):
        pass


# from https://github.com/brosner/django-timezones/pull/13
try:
    from south.modelsinspector import (add_introspection_rules,
                                       add_ignored_fields)
    add_ignored_fields(["^taggit\.managers"])
    add_introspection_rules(rules=[(
            (TimeZoneField,),   # Class(es) these apply to
            [],                 # Positional arguments (not used)
            {                   # Keyword argument
            "max_length": ["max_length", {"default": MAX_TIMEZONE_LENGTH}],
            }
            )],
        patterns=['timezones\.fields\.'])
except ImportError:
    pass
Ejemplo n.º 32
0
import django
from django.contrib.contenttypes import generic
from django.db import DEFAULT_DB_ALIAS, connection
from django.contrib.contenttypes.models import ContentType

try:
    from south.modelsinspector import add_ignored_fields
except ImportError:  # South not installed.
    pass
else:
    add_ignored_fields(["^widgy\.generic\.ProxyGenericRelation",
                        "^widgy\.generic\.ProxyGenericForeignKey",
                        "^widgy\.generic\.WidgyGenericForeignKey"])


class ProxyGenericForeignKey(generic.GenericForeignKey):
    def __init__(self, *args, **kwargs):
        kwargs['for_concrete_model'] = False
        super(ProxyGenericForeignKey, self).__init__(*args, **kwargs)


class ProxyGenericRelation(generic.GenericRelation):
    def __init__(self, *args, **kwargs):
        kwargs['for_concrete_model'] = False
        super(ProxyGenericRelation, self).__init__(*args, **kwargs)


class WidgyGenericForeignKey(ProxyGenericForeignKey):
    def __get__(self, instance, instance_type=None):
        try:
            return super(WidgyGenericForeignKey, self).__get__(instance, instance_type)
            object in memory must be used in order for the property to be
            assigned to the correct instance of the object in memory.

            Keyword arguments:
            content_object -- the object that the property should be added to,
                              which must inherit from BaseModel.
            """

            kwargs[self.content_type_field_name] = self.content_type
            kwargs[self.object_id_field_name] = self.pk_val
            db = router.db_for_write(self.model, instance=self.instance)
            obj = super(
                BaseGenericRelatedObjectManager,
                self
            ).using(db).create(**kwargs)

            if content_object and hasattr(content_object, 'set_attribute'):
                content_object.set_attribute(obj.name, obj.value)

            return obj
        create.alters_data = True

    return BaseGenericRelatedObjectManager


try:
    # We need this to support South properly.
    from south.modelsinspector import add_ignored_fields, add_introspection_rules
    add_ignored_fields(["^playerproject\.libs\.model\.generic\.BaseGenericRelation"])
except:
    pass
Ejemplo n.º 34
0
#############################################################

from django.utils.text import capfirst
from django.core import exceptions

#### import per eav #####
import os
project = os.path.basename(os.path.dirname(__file__))
os.environ['DJANGO_SETTINGS_MODULE'] = '%s.settings' % project
import eav
from eav.forms import BaseDynamicEntityForm
from eav.models import Attribute

from south.modelsinspector import add_ignored_fields
add_ignored_fields(["^eav\.fields\.EavDatatypeField"])
add_ignored_fields(["^eav\.fields\.EavSlugField"])

#### fine import eav ####

class MultiSelectFormField(forms.MultipleChoiceField):
    widget = forms.CheckboxSelectMultiple
 
    def __init__(self, *args, **kwargs):
        self.max_choices = kwargs.pop('max_choices', 0)
        super(MultiSelectFormField, self).__init__(*args, **kwargs)
 
    def clean(self, value):
        if not value and self.required:
            raise forms.ValidationError(self.error_messages['required'])
        # if value and self.max_choices and len(value) > self.max_choices:
Ejemplo n.º 35
0
from drumbeat.utils import get_partition_id, safe_filename
from drumbeat.models import ModelBase
from relationships.models import Relationship
from projects.models import Project, Participation
from notifications.models import send_notifications
from activity.schema import object_types
from users.managers import CategoryTaggableManager
from richtext.models import RichTextField
from tracker import statsd

import caching.base

log = logging.getLogger(__name__)

# To fix a South problem (Cannot freeze field 'users.userprofile.tags')
add_ignored_fields(["^users\.managers"])

GRAVATAR_TEMPLATE = ("https://secure.gravatar.com/avatar/%(gravatar_hash)s"
                     "?s=%(size)s&d=%(default)s&r=%(rating)s")


def determine_upload_path(instance, filename):
    chunk_size = 1000  # max files per directory
    return "images/profiles/%(partition)d/%(filename)s" % {
        'partition': get_partition_id(instance.pk, chunk_size),
        'filename': safe_filename(filename),
    }


def get_hexdigest(algorithm, salt, raw_password):
    """Generate password hash."""
Ejemplo n.º 36
0
from django.db import models
from django.utils.translation import ugettext as _
from qi_toolkit.models import SimpleSearchableModel, TimestampModelMixin
from django.db.models.signals import post_save, pre_delete
from django.template.defaultfilters import slugify
from django.db import transaction

from south.modelsinspector import add_ignored_fields
add_ignored_fields(["^generic_tags\.manager.TaggableManager"])

from generic_tags import BLANK_TAGSET_NAME

from accounts.models import AccountBasedModel

class TagSet(AccountBasedModel, TimestampModelMixin):
    name = models.CharField(max_length=255, blank=True, null=True)
    order = models.IntegerField(default=0)
    slug = models.SlugField(max_length=255)

    def __unicode__(self):
        return "%s" % self.name

    def save(self, *args, **kwargs):
        if self.name == None or self.name == "":
            self.name = BLANK_TAGSET_NAME

        self.slug = slugify(self.name)
        super(TagSet,self).save(*args, **kwargs)

    class Meta(object):
        ordering = ("order",)
Ejemplo n.º 37
0
import decimal
from datetime import datetime

from django.db import models, connection, transaction
from django.utils.translation import ugettext_lazy as _

from django_extensions.db import fields

from mdqweb.postgres_fts import models as fts_models

from south.modelsinspector import add_ignored_fields

# add_ignored_fields(["^mdqweb\.postgres_fts\.models\.VectorField",
#                     "^django_extensions\.db\.fields\.AutoSlugField",
#                     "^django_extensions\.db\.fields\.CreationDateTimeField"])
add_ignored_fields(["^mdqweb\.postgres_fts\.models\.VectorField"])


##### BEGIN Monkeypatch de AutoSlugField y CreationDateTimeField
# backporteado de aca: https://raw.github.com/django-extensions/django-extensions/master/django_extensions/db/fields/__init__.py
def autoslug_south_field_triple(self):
    "Returns a suitable description of this field for South."
    # We'll just introspect the _actual_ field.
    from south.modelsinspector import introspector
    field_class = "django.db.models.fields.SlugField"
    args, kwargs = introspector(self)
    # That's our definition!
    return (field_class, args, kwargs)


def creationdatetime_south_field_triple(self):
Ejemplo n.º 38
0
            object in memory must be used in order for the property to be
            assigned to the correct instance of the object in memory.

            Keyword arguments:
            content_object -- the object that the property should be added to,
                              which must inherit from BaseModel.
            """

            kwargs[self.content_type_field_name] = self.content_type
            kwargs[self.object_id_field_name] = self.pk_val
            db = router.db_for_write(self.model, instance=self.instance)
            obj = super(BaseGenericRelatedObjectManager,
                        self).using(db).create(**kwargs)

            if content_object and hasattr(content_object, 'set_attribute'):
                content_object.set_attribute(obj.name, obj.value)

            return obj

        create.alters_data = True

    return BaseGenericRelatedObjectManager


try:
    # We need this to support South properly.
    from south.modelsinspector import add_ignored_fields, add_introspection_rules
    add_ignored_fields(
        ["^playerproject\.libs\.model\.generic\.BaseGenericRelation"])
except:
    pass
Ejemplo n.º 39
0
    def __repr__(self):
        return "<{0} for {1}.{2}>".format(self.__class__.__name__, self.field.model.__name__, self.field.name)


class LanguageCodeDescriptor(object):
    """
    This is the property to access the ``language_code`` in the ``TranslatableModel``.
    """
    def __get__(self, instance, instance_type=None):
        if not instance:
            raise AttributeError("language_code must be accessed via instance")

        return instance._current_language

    def __set__(self, instance, value):
        raise AttributeError("The 'language_code' attribute cannot be changed directly! Use the set_current_language() method instead.")

    def __delete__(self, instance):
        raise AttributeError("The 'language_code' attribute cannot be deleted!")


try:
    from south.modelsinspector import add_ignored_fields
except ImportError:
    pass
else:
    _name_re = "^" + __name__.replace(".", "\.")
    add_ignored_fields((
        _name_re + "\.TranslatedField",
    ))
Ejemplo n.º 40
0
import decimal
from datetime import datetime

from django.db import models, connection, transaction
from django.utils.translation import ugettext_lazy as _

from django_extensions.db import fields

from moronweb.postgres_fts import models as fts_models

from south.modelsinspector import add_ignored_fields

# add_ignored_fields(["^moronweb\.postgres_fts\.models\.VectorField",
#                     "^django_extensions\.db\.fields\.AutoSlugField",
#                     "^django_extensions\.db\.fields\.CreationDateTimeField"])
add_ignored_fields(["^moronweb\.postgres_fts\.models\.VectorField"])


##### BEGIN Monkeypatch de AutoSlugField y CreationDateTimeField
# backporteado de aca: https://raw.github.com/django-extensions/django-extensions/master/django_extensions/db/fields/__init__.py
def autoslug_south_field_triple(self):
    "Returns a suitable description of this field for South."
    # We'll just introspect the _actual_ field.
    from south.modelsinspector import introspector
    field_class = "django.db.models.fields.SlugField"
    args, kwargs = introspector(self)
    # That's our definition!
    return (field_class, args, kwargs)

def creationdatetime_south_field_triple(self):
    "Returns a suitable description of this field for South."
Ejemplo n.º 41
0
class I4pProject(TranslatableModel):
    """
    Root object for a project. Holds only shared data
    """

    STATUS_CHOICES = [
        ('IDEA', _('Concept')),
        ('BEGIN', _('Starting')),
        ('WIP', _('In development')),
        ('END', _('Mature')),
    ]

    PROGRESS_CHOICES = [
        ("EDIT", _("In edition")),
        ("FULL", _("Complete")),
    ]

    author = models.ForeignKey(I4pProfile,
                               verbose_name=_("author"),
                               null=True,
                               blank=True)
    ip_addr = models.CharField(max_length=15, null=True, blank=True)

    members = models.ManyToManyField(
        User,
        verbose_name=_("members"),
        through='ProjectMember',
        related_name='projects',
    )

    fans = models.ManyToManyField(
        User,
        verbose_name=_("fans"),
        through='ProjectFan',
        related_name='fan_of_projects',
    )

    best_of = models.BooleanField(verbose_name=_('best of'), default=False)

    created = models.DateTimeField(verbose_name=_("creation date"),
                                   auto_now_add=True)

    objectives = models.ManyToManyField(Objective,
                                        verbose_name=_('objectives'),
                                        null=True,
                                        blank=True)

    website = models.URLField(verbose_name=_('website'),
                              verify_exists=False,
                              max_length=200,
                              null=True,
                              blank=True)

    status = models.CharField(verbose_name=_('status'),
                              max_length=5,
                              choices=STATUS_CHOICES,
                              default="IDEA",
                              null=True,
                              blank=True)

    project_leader_info = models.TextField(
        verbose_name=_('project leader information'), null=True, blank=True)

    locations = models.ManyToManyField(
        Location,
        verbose_name=_('locations'),
    )

    references = models.ManyToManyField(ProjectReference,
                                        null=True,
                                        blank=True)

    topics = models.ManyToManyField(SiteTopic,
                                    verbose_name=_('topics'),
                                    related_name='projects')

    cover_picture = models.ForeignKey('ProjectPicture', null=True, blank=True)

    # dynamicsites
    site = models.ManyToManyField(
        Site,
        help_text=_('The sites on which this project sheet is accessible.'),
        verbose_name=_("sites"),
        related_name='projects')
    objects = TranslationManager()
    on_site = CurrentSiteTranslationManager()

    add_ignored_fields(["^dynamicsites\.fields\.FolderNameField"])
    add_ignored_fields(["^dynamicsites\.fields\.SubdomainListField"])

    translations = TranslatedFields(
        meta={'unique_together': [('language_code', 'slug')]},
        language_code=models.CharField(_('language'),
                                       max_length=6,
                                       choices=settings.LANGUAGES),
        title=models.CharField(_("title"),
                               max_length=80,
                               default=_("My Project Title")),
        slug=AutoSlugField(populate_from="title",
                           always_update=True,
                           unique_with=['language_code']),
        completion_progress=models.CharField(verbose_name=_('status'),
                                             max_length=5,
                                             choices=PROGRESS_CHOICES,
                                             default="EDIT",
                                             null=True,
                                             blank=True),
        modified=models.DateTimeField(null=True, blank=True),
        baseline=models.CharField(verbose_name=_("one line description"),
                                  max_length=180,
                                  null=True,
                                  blank=True,
                                  default=_("One line description")),
        about_section=models.TextField(_("about the project"),
                                       null=True,
                                       blank=True),
        partners_section=models.TextField(
            _("who are the partners of this project"), null=True, blank=True),
        callto_section=models.TextField(_("Help request"),
                                        null=True,
                                        blank=True),
        themes=TagField(_("Themes of the project"), null=True, blank=True),
    )

    def get_primary_picture(self):
        """
        Return the first picture, if available
        """
        if len(self.pictures.all()):
            return self.pictures.all()[0]
        else:
            return None

    def get_current_translation(self):
        """
        Get the translation model (hvad) from the current shared
        model instance
        """
        return get_cached_translation(self)

    def __unicode__(self):
        return self.lazy_translation_getter('title', 'Project: %s' % self.pk)

    def get_absolute_url(self):
        current_language = translation.get_language()

        # Don't move this into the 'activate' block or hvad will get
        # crazy with the language change
        slug = self.lazy_translation_getter('slug')

        translation.activate(self.language_code)
        url = reverse('project_sheet-show', kwargs={'slug': slug})
        translation.activate(current_language)

        return url
Ejemplo n.º 42
0
    ('VC', _('St. Vincent & the Grenadines')),
    ('VE', _('Venezuela')),
    ('VG', _('British Virgin Islands')),
    ('VI', _('United States Virgin Islands')),
    ('VN', _('Viet Nam')),
    ('VU', _('Vanuatu')),
    ('WF', _('Wallis & Futuna Islands')),
    ('WS', _('Samoa')),
    ('YE', _('Yemen')),
    ('YT', _('Mayotte')),
    ('YU', _('Yugoslavia')),
    ('ZA', _('South Africa')),
    ('ZM', _('Zambia')),
    ('ZR', _('Zaire')),
    ('ZW', _('Zimbabwe')),
    ('ZZ', _('Unknown or unspecified country')),
)

class CountryField(models.CharField):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault('max_length', 2)
        kwargs.setdefault('choices', COUNTRIES)

        super(CountryField, self).__init__(*args, **kwargs)

    def get_internal_type(self):
        return "CharField"

from south.modelsinspector import add_ignored_fields 
add_ignored_fields(["^webEval\.web_eval__core\.country_field__helper.CountryField"]) 
Ejemplo n.º 43
0
        self.get_tagged_item_manager().clear()


class ClusterTaggableManager(TaggableManager):
    def __get__(self, instance, model):
        # override TaggableManager's requirement for instance to have a primary key
        # before we can access its tags
        try:
            manager = _ClusterTaggableManager(through=self.through,
                                              model=model,
                                              instance=instance,
                                              prefetch_cache_name=self.name)
        except TypeError:  # fallback for django-taggit pre 0.11
            manager = _ClusterTaggableManager(through=self.through,
                                              model=model,
                                              instance=instance)

        return manager

    def value_from_object(self, instance):
        # retrieve the queryset via the related manager on the content object,
        # to accommodate the possibility of this having uncommitted changes relative to
        # the live database
        rel_name = self.through._meta.get_field(
            'content_object').related.get_accessor_name()
        return getattr(instance, rel_name).all()


# tell south to ignore ClusterTaggableManager, like it ignores taggit.TaggableManager
add_ignored_fields(["^modelcluster\.tags\.ClusterTaggableManager"])
Ejemplo n.º 44
0
                    .format(self.model._meta.object_name, self.name, self.slot)
                )

    def value_from_object(self, obj):
        """
        Internal Django method, used to return the placeholder ID when exporting the model instance.
        """
        try:
            # not using self.attname, access the descriptor instead.
            placeholder = getattr(obj, self.name)
        except Placeholder.DoesNotExist:
            return None  # Still allow ModelForm / admin to open and create a new Placeholder if the table was truncated.

        return placeholder.id if placeholder else None  # Be consistent with other fields, like ForeignKey


if django.VERSION < (1, 7):
    try:
        from south.modelsinspector import add_ignored_fields
    except ImportError:
        pass
    else:
        # South 0.7.x ignores GenericRelation fields but doesn't ignore subclasses.
        # Taking the same fix as applied in http://south.aeracode.org/ticket/414
        _name_re = "^" + __name__.replace(".", "\.")
        add_ignored_fields((
            _name_re + "\.PlaceholderField",
            _name_re + "\.PlaceholderRelation",
            _name_re + "\.ContentItemRelation",
        ))
Ejemplo n.º 45
0
            self.field.name)[0].verbose_name


class LanguageCodeDescriptor(object):
    """
    This is the property to access the ``language_code`` in the ``TranslatableModel``.
    """
    def __get__(self, instance, instance_type=None):
        if not instance:
            raise AttributeError("language_code must be accessed via instance")

        return instance._current_language

    def __set__(self, instance, value):
        raise AttributeError(
            "The 'language_code' attribute cannot be changed directly! Use the set_current_language() method instead."
        )

    def __delete__(self, instance):
        raise AttributeError(
            "The 'language_code' attribute cannot be deleted!")


try:
    from south.modelsinspector import add_ignored_fields
except ImportError:
    pass
else:
    _name_re = "^" + __name__.replace(".", "\.")
    add_ignored_fields((_name_re + "\.TranslatedField", ))
Ejemplo n.º 46
0
import django
from django.contrib.contenttypes import generic
from django.db import DEFAULT_DB_ALIAS, connection
from widgy.generic.models import ContentType

try:
    from south.modelsinspector import add_ignored_fields
except ImportError:  # South not installed.
    pass
else:
    add_ignored_fields([
        "^widgy\.generic\.ProxyGenericRelation",
        "^widgy\.generic\.ProxyGenericForeignKey",
        "^widgy\.generic\.WidgyGenericForeignKey"
    ])

if django.VERSION >= (1, 6):

    class ProxyGenericForeignKey(generic.GenericForeignKey):
        def __init__(self, *args, **kwargs):
            kwargs['for_concrete_model'] = False
            super(ProxyGenericForeignKey, self).__init__(*args, **kwargs)

    class ProxyGenericRelation(generic.GenericRelation):
        def __init__(self, *args, **kwargs):
            kwargs['for_concrete_model'] = False
            super(ProxyGenericRelation, self).__init__(*args, **kwargs)
else:

    class ProxyGenericForeignKey(generic.GenericForeignKey):
        """
Ejemplo n.º 47
0
from drumbeat import storage
from drumbeat.utils import get_partition_id, safe_filename
from drumbeat.models import ModelBase
from relationships.models import Relationship
from projects.models import Project, Participation
from users import tasks
from activity.schema import object_types
from users.managers import CategoryTaggableManager

import caching.base

log = logging.getLogger(__name__)

# To fix a South problem (Cannot freeze field 'users.userprofile.tags')
add_ignored_fields(["^users\.managers"])

GRAVATAR_TEMPLATE = ("http://www.gravatar.com/avatar/%(gravatar_hash)s"
                     "?s=%(size)s&amp;d=%(default)s&amp;r=%(rating)s")


def determine_upload_path(instance, filename):
    chunk_size = 1000  # max files per directory
    return "images/profiles/%(partition)d/%(filename)s" % {
        'partition': get_partition_id(instance.pk, chunk_size),
        'filename': safe_filename(filename),
    }


def get_hexdigest(algorithm, salt, raw_password):
    """Generate password hash."""
from django.contrib.contenttypes.generic import GenericRelation
from genericm2m.models import RelatedObjectsDescriptor

from .models import RelatedContent


class ReverseRelatedObjectsField(RelatedObjectsDescriptor):
    def __init__(self, model=None, from_field="destination_object",
            to_field="source_object"):
        if not model:
            model = RelatedContent
        super(ReverseRelatedObjectsField, self).__init__(
                model, from_field, to_field)


class RelatedContentField(GenericRelation):
    def __init__(self, **kwargs):
        defaults = {
            "object_id_field": "source_id",
            "content_type_field": "source_type",
        }
        defaults.update(kwargs)
        super(RelatedContentField, self).__init__(RelatedContent, **defaults)

from south.modelsinspector import add_ignored_fields
add_ignored_fields(["^armstrong\.apps\.related_content\.fields\.RelatedContentField"])
Ejemplo n.º 49
0
            except extensions.PluginNotFound as e:
                raise extensions.PluginNotFound(str(e) + " Update the plugin list of '{0}.{1}' field or FLUENT_CONTENTS_PLACEHOLDER_CONFIG['{2}'] setting.".format(self.model._meta.object_name, self.name, self.slot))

    def value_from_object(self, obj):
        """
        Internal Django method, used to return the placeholder ID when exporting the model instance.
        """
        try:
            # not using self.attname, access the descriptor instead.
            placeholder = getattr(obj, self.name)
        except Placeholder.DoesNotExist:
            return None   # Still allow ModelForm / admin to open and create a new Placeholder if the table was truncated.

        return placeholder.id if placeholder else None  # Be consistent with other fields, like ForeignKey


if django.VERSION < (1, 7):
    try:
        from south.modelsinspector import add_ignored_fields
    except ImportError:
        pass
    else:
        # South 0.7.x ignores GenericRelation fields but doesn't ignore subclasses.
        # Taking the same fix as applied in http://south.aeracode.org/ticket/414
        _name_re = "^" + __name__.replace(".", "\.")
        add_ignored_fields((
            _name_re + "\.PlaceholderField",
            _name_re + "\.PlaceholderRelation",
            _name_re + "\.ContentItemRelation",
        ))
Ejemplo n.º 50
0
class AnnotatedModel(models.Model):
    annotations = AnnotationSet()

    @property
    def vals(self):
        return self.annotations.vals

    @vals.setter
    def vals(self, vals):
        AnnotationType = swapper.load_model('annotate', 'AnnotationType')
        types, success = AnnotationType.objects.resolve_names(*(vals.keys()))
        if not success:
            missing = [name for name, atype in types.items() if atype is None]
            raise TypeError(
                "Could not identify one or more annotation types: %s!"
                % missing
            )

        for name, atype in types.items():
            annot, is_new = self.annotations.get_or_create(type=atype)
            annot.value = vals[name]
            annot.save()

    class Meta:
        abstract = True

# Tell south not to worry about the "custom" field type
from south.modelsinspector import add_ignored_fields
add_ignored_fields(["^wq.db.patterns.annotate.models.AnnotationSet"])
Ejemplo n.º 51
0
            return (name, path, args, { 'default': kwargs.get('default')})
    
    # support DateTimeField
    if BaseField == models.DateTimeField and kwargs.get('default') is None:
        import datetime
        kwargs['default'] = datetime.datetime.utcnow()
    
    # support Date and DateTime in django-rest-framework-hstore
    if BaseField == models.DateTimeField or BaseField == models.DateField:
        def value_to_string(self, obj):
            val = self._get_val_from_obj(obj)
            try:
                return '' if val is None else val.isoformat()
            except AttributeError as e:
                return val
        VirtualField.value_to_string = value_to_string
    
    field = VirtualField(**kwargs)
    
    if field.default == models.fields.NOT_PROVIDED:
        field.default = ''
    
    return field


# south compatibility, ignore virtual fields
try:
    from south.modelsinspector import add_ignored_fields
    add_ignored_fields(["^django_hstore\.virtual\.VirtualField"])
except ImportError:
    pass
Ejemplo n.º 52
0
            return (name, path, args, { 'default': kwargs.get('default')})
    
    # support DateTimeField
    if BaseField == models.DateTimeField and kwargs.get('default') is None:
        import datetime
        kwargs['default'] = datetime.datetime.utcnow()
    
    # support Date and DateTime in django-rest-framework-hstore
    if BaseField == models.DateTimeField or BaseField == models.DateField:
        def value_to_string(self, obj):
            val = self._get_val_from_obj(obj)
            try:
                return '' if val is None else val.isoformat()
            except AttributeError as e:
                return val
        VirtualField.value_to_string = value_to_string
    
    field = VirtualField(**kwargs)
    
    if field.default == models.fields.NOT_PROVIDED:
        field.default = ''
    
    return field


# south compatibility, ignore virtual fields
try:
    from south.modelsinspector import add_ignored_fields
    add_ignored_fields(["^django_hstore\.virtual\.VirtualField"])
except ImportError:
    pass
Ejemplo n.º 53
0
class RelatedVideosField(RelatedMediaField):
    to = VideoRelation
    mediatype = Video


#####################
# Media Collections #
#####################

class MediaCollection(models.Model):
    name = models.CharField(max_length=100)
    slug = AutoSlugField(max_length=200, unique=True, editable=False, prepopulate_from='name',
            help_text='Unique text identifier used in urls.')
    description = models.TextField(blank=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('name',)
        abstract = True

    def __unicode__(self):
        return self.name

# South Introspection Rules
try:
    from south.modelsinspector import add_ignored_fields
    add_ignored_fields(["^.+\.apps\.media\.models"])
except ImportError:
    pass
Ejemplo n.º 54
0
            )
            current_index = ids.index(current_rel.id)
            if current_index == 0:
                # A negative index will currently raise an AssertionError,
                # but who knows what the future will bring? Let's just return.
                return None
            previous_rel = self.get(id=ids[current_index - 1])
            return previous_rel
        except (ValueError, IndexError):
            return None


# LowerCaseTaggableManager needs to be ignored by South; it inherits from
# django-taggit's TaggableManager which is already ignored by default.
from south.modelsinspector import add_ignored_fields
add_ignored_fields(['^core\.managers\.LowerCaseTaggableManager'])

################################################################################
# The add() method defined in django-taggit's _TaggableManager causes an       #
# infinite loop when an existing tag is 'added' again with a different         #
# combination of upper and lower case letters. Because the logic that looks    #
# for existing tags is in add() case-sensitive, whereas LowerCaseTag's save()  #
# method is not, the same tag is always considered new causing a World of      #
# Hurt.                                                                        #
#                                                                              #
# Monkey patching our Topic's tag manager proved to be infeasible, hence       #
# the two Manager classes below. The only difference from the original         #
# django-taggit code is that the tags in add() are all lower-cased, and that   #
# _TaggableManager is replaced with _LowerCaseTaggableManager in __get__().    #
################################################################################