<commit_before>import time
from datetime import datetime

from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models import signals

import tagging
from content.managers import PermittedManager
from content.utils import generate_slug
from photologue.models import ImageModel

class ModelBase(ImageModel):
    objects = models.Manager()
    permitted = PermittedManager()
    
    state = models.CharField(
        max_length=32,
        choices=(
            ('unpublished', 'Unpublished'),
            ('published', 'Published'),
            ('staging', 'Staging'),
        ),
        default='unpublished',
        help_text="Set the item state. The 'Published' state makes the item visible to the public, 'Unpublished' retracts it and 'Staging' makes the item visible to staff users.",
        blank=True,
        null=True,
    )
    slug = models.SlugField(
        editable=False,
        max_length=255,
        db_index=True,
        unique=True,
    )
    title = models.CharField(
        max_length=200, help_text='A short descriptive title.',
    )
    description = models.TextField(
        help_text='A short description. More verbose than the title but limited to one or two sentences.',
        blank=True,
        null=True,
    )
    created = models.DateTimeField(
        'Created Date & Time', 
        blank=True,
        help_text='Date and time on which this item was created. This is automatically set on creation, but can be changed subsequently.'
    )
    modified = models.DateTimeField(
        'Modified Date & Time', 
        editable=False,
        help_text='Date and time on which this item was last modified. This is automatically set each time the item is saved.'
    )
    owner = models.ForeignKey(
        User, 
        blank=True,
        null=True,
    )
    content_type = models.ForeignKey(
        ContentType, 
        editable=False, 
        null=True
    )
    class_name = models.CharField(
        max_length=32, 
        editable=False, 
        null=True
    )
    categories = models.ManyToManyField(
        'category.Category',
        blank=True,
        null=True,
        help_text='Categorizing this item.'
    )
    tags = tagging.fields.TagField()
    sites = models.ManyToManyField(
        'sites.Site',
        blank=True,
        null=True,
        help_text='Makes item eligible to be published on selected sites.',
    )
    publishers = models.ManyToManyField(
        'publisher.Publisher',
        blank=True,
        null=True,
        help_text='Makes item eligible to be published on selected platform.',
    )
   
    class Meta:
        ordering = ('-created',)
    
    def as_leaf_class(self):
        """
        Returns the leaf class no matter where the calling instance is in the inheritance hierarchy.
        Inspired by http://www.djangosnippets.org/snippets/1031/
        """
        try:
            return self.__getattribute__(self.classname.lower())
        except AttributeError:
            content_type = self.content_type
            model = content_type.model_class()
            if(model == ModelBase):
                return self
            return model.objects.get(id=self.id)
        
    def save(self, *args, **kwargs):
        # set created time to now on initial save.
        if not self.id and not self.created:
            self.created = datetime.now()
        # set modified to now on each save 
        self.modified = datetime.now()
       
        # set leaf class content type
        if not self.content_type:
            self.content_type = ContentType.objects.get_for_model(self.__class__)
        
        # set leaf class class name
        if not self.class_name:
            self.class_name = self.__class__.__name__

        # set title as slug uniquely
        self.slug = generate_slug(self, self.title)
        super(ModelBase, self).save(*args, **kwargs)

def set_managers(sender, **kwargs):
    """
    Make sure all classes have the appropriate managers 
    """
    cls = sender

    if issubclass(cls, ModelBase):
        cls.add_to_class('permitted', PermittedManager())

signals.class_prepared.connect(set_managers)<commit_msg>register modelbase for voting and add vote_total property<commit_after>import time
from datetime import datetime

from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models import signals

import tagging
import secretballot
from content.managers import PermittedManager
from content.utils import generate_slug
from photologue.models import ImageModel

class ModelBase(ImageModel):
    objects = models.Manager()
    permitted = PermittedManager()
    
    state = models.CharField(
        max_length=32,
        choices=(
            ('unpublished', 'Unpublished'),
            ('published', 'Published'),
            ('staging', 'Staging'),
        ),
        default='unpublished',
        help_text="Set the item state. The 'Published' state makes the item visible to the public, 'Unpublished' retracts it and 'Staging' makes the item visible to staff users.",
        blank=True,
        null=True,
    )
    slug = models.SlugField(
        editable=False,
        max_length=255,
        db_index=True,
        unique=True,
    )
    title = models.CharField(
        max_length=200, help_text='A short descriptive title.',
    )
    description = models.TextField(
        help_text='A short description. More verbose than the title but limited to one or two sentences.',
        blank=True,
        null=True,
    )
    created = models.DateTimeField(
        'Created Date & Time', 
        blank=True,
        help_text='Date and time on which this item was created. This is automatically set on creation, but can be changed subsequently.'
    )
    modified = models.DateTimeField(
        'Modified Date & Time', 
        editable=False,
        help_text='Date and time on which this item was last modified. This is automatically set each time the item is saved.'
    )
    owner = models.ForeignKey(
        User, 
        blank=True,
        null=True,
    )
    content_type = models.ForeignKey(
        ContentType, 
        editable=False, 
        null=True
    )
    class_name = models.CharField(
        max_length=32, 
        editable=False, 
        null=True
    )
    categories = models.ManyToManyField(
        'category.Category',
        blank=True,
        null=True,
        help_text='Categorizing this item.'
    )
    tags = tagging.fields.TagField()
    sites = models.ManyToManyField(
        'sites.Site',
        blank=True,
        null=True,
        help_text='Makes item eligible to be published on selected sites.',
    )
    publishers = models.ManyToManyField(
        'publisher.Publisher',
        blank=True,
        null=True,
        help_text='Makes item eligible to be published on selected platform.',
    )
   
    class Meta:
        ordering = ('-created',)
    
    def as_leaf_class(self):
        """
        Returns the leaf class no matter where the calling instance is in the inheritance hierarchy.
        Inspired by http://www.djangosnippets.org/snippets/1031/
        """
        try:
            return self.__getattribute__(self.classname.lower())
        except AttributeError:
            content_type = self.content_type
            model = content_type.model_class()
            if(model == ModelBase):
                return self
            return model.objects.get(id=self.id)
        
    def save(self, *args, **kwargs):
        # set created time to now on initial save.
        if not self.id and not self.created:
            self.created = datetime.now()
        # set modified to now on each save 
        self.modified = datetime.now()
       
        # set leaf class content type
        if not self.content_type:
            self.content_type = ContentType.objects.get_for_model(self.__class__)
        
        # set leaf class class name
        if not self.class_name:
            self.class_name = self.__class__.__name__

        # set title as slug uniquely
        self.slug = generate_slug(self, self.title)
        super(ModelBase, self).save(*args, **kwargs)

    @property
    def vote_total(self):
        """
        Calculates vote total as total_upvotes - total_downvotes. We are adding a method here instead of relying on django-secretballot's addition since that doesn't work for subclasses.
        """
        return self.votes.filter(vote=+1).count() - self.votes.filter(vote=-1).count() 

def set_managers(sender, **kwargs):
    """
    Make sure all classes have the appropriate managers 
    """
    cls = sender
   
    if issubclass(cls, ModelBase):
        cls.add_to_class('permitted', PermittedManager())

signals.class_prepared.connect(set_managers)

# enable voting for ModelBase, but specify a diffirent total name 
# so ModelBase's vote_total method is not overwritten
secretballot.enable_voting_on(ModelBase, total_name="secretballot_added_vote_total")
{'fraction_non_alphanumeric': 0.08572681429511073, 'fraction_numerical': 0.00328875246656435, 'mean_word_length': 2.355277675616035, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '4393672', 'n_tokens_mistral': 2520, 'n_tokens_neox': 2449, 'n_words': 729}