Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.7 kB
1
Indexable
Never
# -*- coding: utf-8 -*-
from django.conf import settings
from django.urls import reverse
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _
from django.utils.text import slugify
from moviesap.apps.core.utils import generate_random_string
from sorl.thumbnail import ImageField

class Category(models.Model):

    def upload_location(instance, filename):
        #filebase, extension = filename.split(".")
        # return "%s/%s.%s" %(instance.id, instance.id, extension)
        try:
            CategoryModel = instance.__class__
            new_id = CategoryModel.objects.order_by("id").last().id + 1
        except:
            new_id = 1
        return "{} {}".format(new_id, filename)
    # Relations
    # Attributes - Mandatory
    title = models.CharField(
        max_length=200,
        verbose_name=_("title"),
        help_text=_("Enter the Category title"))
    color = models.CharField(max_length=7, default='#007bff')
    slug = models.SlugField(unique=True)
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)
    image = models.ImageField(
        null=True,
        blank=True,
        upload_to=upload_location,
        height_field="height_field",
        width_field="width_field",)
    created_at = models.DateTimeField(
        auto_now=True,
        auto_now_add=False,
        verbose_name=("created_at"))
    updated_at = models.DateTimeField(
        auto_now_add=True,
        auto_now=False,
        verbose_name=_("updated_at"),
        help_text=_("Enter a new date"))
    # Attributes - Optional
    # Custom Properties

    # Methods
    def get_absolute_url(self):
        return reverse("categories:detail", kwargs={"slug": self.slug})

 
    def get_html_badge(self):
        name = escape(self.name)
        color = escape(self.color)
        html = '<span class="badge badge-primary" style="background-color: %s">%s</span>' % (color, name)
        return mark_safe(html)
    # Meta and String
    class Meta:
        verbose_name = _("Category")
        verbose_name_plural = _("Categories")
        ordering = ['title', ]
        unique_together = ["title"]

    def __str__(self):
        return "{}".format(self.title)


@receiver(pre_save, sender=Category)
def pre_save_category_receiver(sender, instance, raw, using, **kwargs):
    if instance and not instance.slug:
        slug = slugify(instance.title)
        random_string = generate_random_string()
        instance.slug = slug + "_" + random_string


pre_save.connect(pre_save_category_receiver, sender=Category)