<commit_before>from datetime import datetime

from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.sites.models import Site
from django.template.defaultfilters import slugify
from django.core.urlresolvers import reverse
from django.contrib.redirects.models import Redirect

from ella.core.managers import ListingManager, HitCountManager, PlacementManager, RelatedManager
from ella.core.cache import get_cached_object, get_cached_list, CachedGenericForeignKey
from ella.core.models.main import Category, Author, Source
from ella.photos.models import Photo
from ella.core.box import Box

PUBLISH_FROM_WHEN_EMPTY = datetime(3000, 1, 1)

def PublishableBox(publishable, box_type, nodelist, model=None):
    "add some content type info of self.target"
    if not model:
        model = publishable.content_type.model_class()
    box_class = model.box_class

    if box_class == PublishableBox:
        box_class = Box
    return box_class(publishable, box_type, nodelist, model=model)

class Publishable(models.Model):
    """
    Base class for all object that can be published in ella
    """
    box_class = staticmethod(PublishableBox)

    content_type = models.ForeignKey(ContentType)

    category = models.ForeignKey(Category, verbose_name=_('Category'))

    # Titles
    title = models.CharField(_('Title'), max_length=255)
    slug = models.SlugField(_('Slug'), max_length=255)

    # Authors and Sources
    authors = models.ManyToManyField(Author, verbose_name=_('Authors'))
    source = models.ForeignKey(Source, blank=True, null=True, verbose_name=_('Source'))

    # Main Photo
    photo = models.ForeignKey(Photo, blank=True, null=True, verbose_name=_('Photo'))

    # Description
    description = models.TextField(_('Description'), blank=True)

    # denormalized fields
    # the placement's publish_from
    publish_from = models.DateTimeField(_('Publish from'), editable=False, default=PUBLISH_FROM_WHEN_EMPTY, db_index=True)

    class Meta:
        app_label = 'core'
        verbose_name = _('Publishable object')
        verbose_name_plural = _('Publishable objects')

    @property
    def target(self):
        if not hasattr(self, '_target'):
            self._target = self.content_type.get_object_for_this_type(pk=self.pk)
        return self._target

    if 'ella.oldcomments' in settings.INSTALLED_APPS:
        from ella.oldcomments.models import Comment
        comments = generic.GenericRelation(Comment, object_id_field='target_id', content_type_field='target_ct')

    @property
    def main_placement(self):
        " Return object's main placement, that is the object's placement in its primary category "
        if hasattr(self, '_main_placement'):
            return self._main_placement

        current_site = Site.objects.get_current()

        # TODO: what if have got multiple listings on one site?
        placements = get_cached_list(
                Placement,
                publishable=self.pk,
                category__site=current_site,
            )
        if placements:
            if len(placements) == 1:
                self._main_placement = placements[0]
            else:
                # with multiple listings, one with first publish_from
                # primary
                first_published = None
                for placement in placements:
                    if first_published is None or placement.publish_from < first_published.publish_from:
                        first_published = placement

                assert first_published is not None
                self._main_placement = first_published

        else:
            try:
                # TODO - check and if we don't have category, take the only placement that exists in current site
                self._main_placement = get_cached_object(
                        Placement,
                        publishable=self.pk,
                        category=self.category_id
                    )
            except Placement.DoesNotExist:
                self._main_placement = None

        if self._main_placement:
            # preserve memory and SQL queries by using the same object
            self._main_placement.publishable = self

        return self._main_placement

    def get_absolute_url(self, domain=False):
        " Get object's URL. "
        placement = self.main_placement
        if placement:
            return placement.get_absolute_url(domain=domain)

    def get_domain_url(self):
        return self.get_absolute_url(domain=True)

    def get_admin_url(self):
        from ella.ellaadmin.utils import admin_url
        return admin_url(self)

    def save(self, **kwargs):
        self.content_type = ContentType.objects.get_for_model(self)
        if self.pk and hasattr(self, 'slug'): # only run on update
            # get old self
            old_slug = self.__class__._default_manager.get(pk=self.pk).slug
            # the slug has changed
            if old_slug != self.slug:
                for plc in Placement.objects.filter(publishable=self):
                    if plc.slug == old_slug:
                        plc.slug = self.slug
                        plc.save(force_update=True)
        return super(Publishable, self).save(**kwargs)

    def delete(self):
        url = self.get_absolute_url()
        Redirect.objects.filter(new_path=url).delete()
        return super(Publishable, self).delete()

    def __unicode__(self):
        return self.title

# FIXME find another way to register!
if 'tagging' in settings.INSTALLED_APPS:<commit_msg>get_domain_url_admin_tag returns <a> tag of the get_domain_url<commit_after>from datetime import datetime

from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe, mark_for_escaping
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.sites.models import Site
from django.template.defaultfilters import slugify
from django.core.urlresolvers import reverse
from django.contrib.redirects.models import Redirect

from ella.core.managers import ListingManager, HitCountManager, PlacementManager, RelatedManager
from ella.core.cache import get_cached_object, get_cached_list, CachedGenericForeignKey
from ella.core.models.main import Category, Author, Source
from ella.photos.models import Photo
from ella.core.box import Box

PUBLISH_FROM_WHEN_EMPTY = datetime(3000, 1, 1)

def PublishableBox(publishable, box_type, nodelist, model=None):
    "add some content type info of self.target"
    if not model:
        model = publishable.content_type.model_class()
    box_class = model.box_class

    if box_class == PublishableBox:
        box_class = Box
    return box_class(publishable, box_type, nodelist, model=model)

class Publishable(models.Model):
    """
    Base class for all object that can be published in ella
    """
    box_class = staticmethod(PublishableBox)

    content_type = models.ForeignKey(ContentType)

    category = models.ForeignKey(Category, verbose_name=_('Category'))

    # Titles
    title = models.CharField(_('Title'), max_length=255)
    slug = models.SlugField(_('Slug'), max_length=255)

    # Authors and Sources
    authors = models.ManyToManyField(Author, verbose_name=_('Authors'))
    source = models.ForeignKey(Source, blank=True, null=True, verbose_name=_('Source'))

    # Main Photo
    photo = models.ForeignKey(Photo, blank=True, null=True, verbose_name=_('Photo'))

    # Description
    description = models.TextField(_('Description'), blank=True)

    # denormalized fields
    # the placement's publish_from
    publish_from = models.DateTimeField(_('Publish from'), editable=False, default=PUBLISH_FROM_WHEN_EMPTY, db_index=True)

    class Meta:
        app_label = 'core'
        verbose_name = _('Publishable object')
        verbose_name_plural = _('Publishable objects')

    @property
    def target(self):
        if not hasattr(self, '_target'):
            self._target = self.content_type.get_object_for_this_type(pk=self.pk)
        return self._target

    if 'ella.oldcomments' in settings.INSTALLED_APPS:
        from ella.oldcomments.models import Comment
        comments = generic.GenericRelation(Comment, object_id_field='target_id', content_type_field='target_ct')

    @property
    def main_placement(self):
        " Return object's main placement, that is the object's placement in its primary category "
        if hasattr(self, '_main_placement'):
            return self._main_placement

        current_site = Site.objects.get_current()

        # TODO: what if have got multiple listings on one site?
        placements = get_cached_list(
                Placement,
                publishable=self.pk,
                category__site=current_site,
            )
        if placements:
            if len(placements) == 1:
                self._main_placement = placements[0]
            else:
                # with multiple listings, one with first publish_from
                # primary
                first_published = None
                for placement in placements:
                    if first_published is None or placement.publish_from < first_published.publish_from:
                        first_published = placement

                assert first_published is not None
                self._main_placement = first_published

        else:
            try:
                # TODO - check and if we don't have category, take the only placement that exists in current site
                self._main_placement = get_cached_object(
                        Placement,
                        publishable=self.pk,
                        category=self.category_id
                    )
            except Placement.DoesNotExist:
                self._main_placement = None

        if self._main_placement:
            # preserve memory and SQL queries by using the same object
            self._main_placement.publishable = self

        return self._main_placement

    def get_absolute_url(self, domain=False):
        " Get object's URL. "
        placement = self.main_placement
        if placement:
            return placement.get_absolute_url(domain=domain)

    def get_domain_url(self):
        return self.get_absolute_url(domain=True)

    def get_domain_url_admin_tag(self):
        if self.get_domain_url() is not None:
            #return mark_safe(u'<a href="%s">url</a>' % ( self.get_domain_url() ) )
            return mark_safe(u'<a href="%s">url</a>' % ( self.get_domain_url() ) )
        else:
            return self.get_domain_url()
    get_domain_url_admin_tag.short_description = _('URL')
    get_domain_url_admin_tag.allow_tags = True

    def get_admin_url(self):
        from ella.ellaadmin.utils import admin_url
        return admin_url(self)

    def save(self, **kwargs):
        self.content_type = ContentType.objects.get_for_model(self)
        if self.pk and hasattr(self, 'slug'): # only run on update
            # get old self
            old_slug = self.__class__._default_manager.get(pk=self.pk).slug
            # the slug has changed
            if old_slug != self.slug:
                for plc in Placement.objects.filter(publishable=self):
                    if plc.slug == old_slug:
                        plc.slug = self.slug
                        plc.save(force_update=True)
        return super(Publishable, self).save(**kwargs)

    def delete(self):
        url = self.get_absolute_url()
        Redirect.objects.filter(new_path=url).delete()
        return super(Publishable, self).delete()

    def __unicode__(self):
        return self.title

# FIXME find another way to register!
if 'tagging' in settings.INSTALLED_APPS:
{'fraction_non_alphanumeric': 0.07962901069518717, 'fraction_numerical': 0.002339572192513369, 'mean_word_length': 2.6479731789088694, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3373936', 'n_tokens_mistral': 3351, 'n_tokens_neox': 3212, 'n_words': 830}