class ProductoImagen(models.Model):
    producto = models.ForeignKey(Producto)
    imagen = models.ImageField(upload_to='productos')
    thumbnail = ImageSpecField([Resize(152, 152)], source='imagen', options={'quality':60})
    detalle = ImageSpecField([Resize(350, 350)], source='imagen')
    small = ImageSpecField([Resize(62, 62)], source='imagen', options={'quality':60})

    def __unicode__(self):
        return '{0}:'.format(self.id)
Example #2
0
class advertise(models.Model):
    name = models.CharField(max_length=255)
    aprroved = models.BooleanField(default=False)
    reviewed_in = models.DateTimeField(auto_now=True)
    price = models.DecimalField(blank=False, decimal_places=2, max_digits=10)
    category = models.ForeignKey('advertise.category',
                                 on_delete=models.SET_NULL,
                                 null=True)
    number_of_viewer = models.IntegerField(default=1)
    since = models.DateField(auto_now=True)
    details = models.TextField(max_length=255,
                               blank=False,
                               default='not assigned')
    image_1 = ProcessedImageField(upload_to=user_directory_path_1,
                                  blank=True,
                                  processors=[Resize(350, 250)],
                                  format='JPEG',
                                  options={'quality': 100})
    image_2 = ProcessedImageField(upload_to=user_directory_path_2,
                                  blank=True,
                                  processors=[Resize(350, 250)],
                                  format='JPEG',
                                  options={'quality': 100})
    image_3 = ProcessedImageField(upload_to=user_directory_path_3,
                                  blank=True,
                                  processors=[Resize(350, 250)],
                                  format='JPEG',
                                  options={'quality': 100})
    contacts = models.CharField(max_length=11,
                                blank=False,
                                default='01003345516')
    created_by = models.ForeignKey(users,
                                   related_name='creator',
                                   verbose_name='creator',
                                   related_query_name='creator',
                                   on_delete=models.SET_NULL,
                                   null=True,
                                   blank=True)
    reviewed_by = models.ForeignKey(users,
                                    related_name='admin',
                                    verbose_name='admin',
                                    on_delete=models.SET_NULL,
                                    related_query_name='admin',
                                    null=True,
                                    blank=True)

    def __str__(self):
        return self.name

    class Meta:
        app_label = "advertise"
Example #3
0
class Category(models.Model):
    name = models.CharField(max_length=250, default=None)
    image = ProcessedImageField(upload_to=upload_image,
                                blank=True,
                                null=True,
                                validators=[image_extension],
                                processors=[Resize(100, 100)],
                                format='JPEG',
                                options={'quality': 70})
    modified = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-created', )

    def __str__(self):
        return self.name

    def icon(self):
        if self.image != '':
            return "<img src='{}' width=50px>".format(self.image.url)
        else:
            return ''

    icon.allow_tags = True
Example #4
0
class Contact(models.Model):
    TYPES = ((1, _('Contact|social')), (2, _('Contact|other')))

    title = models.CharField(max_length=20,
                             blank=True,
                             verbose_name=_('Contact|title'))
    url_text = models.CharField(max_length=50,
                                blank=True,
                                verbose_name=_('Contact|url_text'))
    url = models.CharField(max_length=100, verbose_name=_('Contact|url'))
    contact_type = models.IntegerField(choices=TYPES,
                                       verbose_name=_('Contact|type'))
    image = ProcessedImageField(upload_to='images/contacts',
                                processors=[Resize(20, 20, False)],
                                format='PNG',
                                verbose_name=_('Contact|image'))
    created_at = models.DateTimeField(auto_now_add=True,
                                      verbose_name=_('Contact|created'))
    updated_at = models.DateTimeField(auto_now=True,
                                      verbose_name=_('Contact|updated'))

    class Meta:
        verbose_name = _('Contact')
        verbose_name_plural = _('Contact|plural')

    def __str__(self):
        return self.title

    def admin_image(self):
        return u'<img src="%s" />' % self.image.url

    admin_image.allow_tags = True
    admin_image.short_description = _('Contact|image')
Example #5
0
class Skript(models.Model):
    key = models.CharField(max_length=20)
    skript = models.TextField(max_length=2000)
    ud = models.ForeignKey(Userdata)
    bild = models.ImageField(upload_to='userskripte', null=True)
    thumbnail = ImageSpecField([WhiteBackground(), Resize(150, 150), ], source='bild', format='png', )

    def __unicode__(self):
        return '%s: %s (%d)' % (self.ud.user.email, self.key, len(self.skript))
Example #6
0
class Post(models.Model):
    title = models.CharField(max_length=50)
    created_date = models.DateTimeField(auto_now_add=True, editable=False)
    modified_date = models.DateTimeField(auto_now=True)
    content1 = models.TextField(default='', blank=True)
    photo1 = ProcessedImageField(blank=True, processors=[Resize(800, 500)])
    content2 = models.TextField(default='', blank=True)
    photo2 = ProcessedImageField(blank=True, processors=[Resize(800, 500)])
    content3 = models.TextField(default='', blank=True)
    photo3 = ProcessedImageField(blank=True, processors=[Resize(800, 500)])
    content4 = models.TextField(default='', blank=True)
    photo4 = ProcessedImageField(blank=True, processors=[Resize(800, 500)])
    content5 = models.TextField(default='', blank=True)
    photo5 = ProcessedImageField(blank=True, processors=[Resize(800, 500)])
    tags = models.CharField(max_length=200, default='', blank=True)

    def __str__(self):
        return self.title
Example #7
0
class Project(models.Model):
    name = models.CharField(max_length=50)
    tech_list = models.TextField(default='', blank=True)
    created_date = models.DateTimeField(auto_now_add=True, editable=False)
    modified_date = models.DateTimeField(auto_now=True)
    content1 = models.TextField(default='', blank=True)
    content2 = models.TextField(default='', blank=True)
    content3 = models.TextField(default='', blank=True)
    content4 = models.TextField(default='', blank=True)
    photo1 = ProcessedImageField(blank=True, processors=[Resize(800, 500)])
    photo2 = ProcessedImageField(blank=True, processors=[Resize(800, 500)])
    photo3 = ProcessedImageField(blank=True, processors=[Resize(800, 500)])
    photo4 = ProcessedImageField(blank=True, processors=[Resize(800, 500)])
    link = models.CharField(max_length=100, default='', blank=True)
    categories = models.CharField(max_length=200, default='', blank=True)

    def __str__(self):
        return self.name
Example #8
0
    def create(self, name, spec, resize=None, save=True):
        """
        Create a new crop with the provided spec. For example the following code
        creates a crop of the original image starting at the X/Y coordinates of 
        0/0 and having a width of 100 pixels and a height of 150 pixels::
                                                                        
            >>> image.crops.create('thumbnail', (0, 0, 100, 150))
        
        Also allows for resizing the crop once it's been done. Useful for scaling
        the crop down to the desired target size::
        
            >>> (x, y, width, height) = crop = 0, 0, 100, 150
            >>> scaled_w, scaled_h = scaled = width / 3 * 2, height / 3 * 2
            >>> image.crops.create('thumbnail', crop, resize = scaled)
        
        Note that you should keep the ratio of width to height when resizing or 
        you'll end up with warped images.
                                         
        :param name: Crop name. This must be unique and is also used to generate
            the filename.
        :param spec: 4-tuple containing ``(x, y, width, height)``
        :param resize: 2-tuple for resizing the crop containing ``(width, height)``
        :param save: Boolean, if specified the model is saved back to DB after the crop.
        """
        name = self.validate_name(name)

        (x, y, width, height) = spec
        spec = {name: dict(x=x, y=y, width=width, height=height)}

        processors = [Crop(**spec[name])]

        if resize is not None:
            processors.append(Resize(resize[0], resize[1]))

        filename = self.get_filename(name)

        spec[name]['filename'] = filename

        # If a crop exists already, delete it first
        if hasattr(self, name):
            self.delete(name, save=False)

        generator = ImageSpec(self.image)
        generator.processors = processors
        content = generator.generate()
        self.field.storage.save(filename, content)

        self.data = dict(self.data, **spec)

        if save:
            self.instance.save()

        return getattr(self, name)
Example #9
0
class Kapitel(models.Model):
    '''Ein Kapitel des "Tutorials".'''

    KATEGORIE_CHOICES = [('0', 'Einstieg'),
                         ('1', 'Schleifen'),
                         ('2', 'Funktionen'),
                         ('3', 'Bedingungen'),
                         ('4', 'Für Fortgeschrittene'),
                        ]

    titel = models.CharField(max_length=50)
    zusammenfassung = models.TextField(max_length=500)
    kategorie = models.CharField(choices=KATEGORIE_CHOICES, max_length=2)
    platz = models.FloatField()
    quelltext = models.TextField(max_length=50000)
    doccoHTML = models.TextField(max_length=100000)
    bild = models.ImageField(upload_to='tutorial')
    docbild = ImageSpecField([WhiteBackground(), Resize(400, 400), ], source='bild', format='JPEG', )
    thumbnail = ImageSpecField([WhiteBackground(), Resize(80, 80), ], source='bild', format='JPEG', )

    def __unicode__(self):
        return u'%s (%s/%d)' % (self.titel, self.kategorie, self.platz)

    def save(self, *args, **kwargs):

        # fill doccoHTML
        sourcefile = tempfile.NamedTemporaryFile(delete=False, dir=settings.TMP_PATH, suffix='.coffee')
        sourcefile.write('# ' + self.titel.encode('utf8') + '\n')
        sourcefile.write('# ' + '-' * len(self.titel.encode('utf8')) + '\n# \n')
        sourcefile.write(self.quelltext.encode('utf8'))
        sourcefile.close()

        path = tempfile.mkdtemp(dir=settings.TMP_PATH)
        os.system('docco -t %s/template.jst -o %s %s' % (settings.DOCCO_TEMPLATE_PATH, path, sourcefile.name))

        with open(os.path.join(path, os.path.basename(sourcefile.name)[:-7] + '.html')) as resultfile:
            self.doccoHTML = resultfile.read().decode('utf8')

        super(Kapitel, self).save(*args, **kwargs)
Example #10
0
class product(models.Model):
    name = models.CharField(max_length=15, blank=False)
    name_ar = models.CharField(max_length=15, blank=False)
    note = models.CharField(max_length=130, blank=True)
    note_ar = models.CharField(max_length=130, blank=True)
    detail = models.TextField(max_length=300, blank=True)
    detail_ar = models.TextField(max_length=300, blank=True)

    price = models.IntegerField()
    image_1 = ProcessedImageField(upload_to=user_directory_path_1,
                                  blank=True,
                                  processors=[Resize(350, 250)],
                                  format='JPEG',
                                  options={'quality': 100})
    image_2 = ProcessedImageField(upload_to=user_directory_path_2,
                                  blank=True,
                                  processors=[Resize(350, 250)],
                                  format='JPEG',
                                  options={'quality': 100})
    image_3 = ProcessedImageField(upload_to=user_directory_path_3,
                                  blank=True,
                                  processors=[Resize(350, 250)],
                                  format='JPEG',
                                  options={'quality': 100})
    image_4 = ProcessedImageField(upload_to=user_directory_path_4,
                                  blank=True,
                                  processors=[Resize(350, 250)],
                                  format='JPEG',
                                  options={'quality': 100})

    def __str__(self):
        return self.name

#now djago will auto delet the old image in case of edit & auto edit ay uploaded image to 250X350 size
#if you have no image form will bbe accepted+

    '''
Example #11
0
class Beispiel(models.Model):
    '''Ein Beispiel in der Gallerie'''

    titel = models.CharField(max_length=50)
    autor = models.CharField(max_length=200)
    quelltext = models.TextField(max_length=50000)
    doccoHTML = models.TextField(max_length=100000)
    bild = models.ImageField(upload_to='tutorial')
    docbild = ImageSpecField([WhiteBackground(), Resize(400, 400), ], source='bild', format='JPEG', )
    thumbnail = ImageSpecField([WhiteBackground(), Resize(200, 200), ], source='bild', format='JPEG', )
    updated = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(Kategorie, null=True, blank=True)

    def __unicode__(self):
        return u'%s (%s)' % (self.titel, unicode(self.updated))

    def save(self, *args, **kwargs):

        # fill doccoHTML
        sourcefile = tempfile.NamedTemporaryFile(delete=False, dir=settings.TMP_PATH, suffix='.coffee')
        sourcefile.write('# ' + self.titel.encode('utf8') + '\n')
        sourcefile.write('# ' + '-' * len(self.titel.encode('utf8')) + '\n#\n#\n')
        if self.quelltext.startswith('#'):
            sourcefile.write('# <div style="margin-top:400px;"></div>\n\n')
        else:
            sourcefile.write('# <div style="margin-top:400px;"></div>\n\n# .\n')
        sourcefile.write(self.quelltext.encode('utf8'))
        sourcefile.close()

        path = tempfile.mkdtemp(dir=settings.TMP_PATH)
        os.system('docco -t %s/template.jst -o %s %s' % (settings.DOCCO_TEMPLATE_PATH, path, sourcefile.name))

        with open(os.path.join(path, os.path.basename(sourcefile.name)[:-7] + '.html')) as resultfile:
            self.doccoHTML = resultfile.read().decode('utf8')

        super(Beispiel, self).save(*args, **kwargs)
Example #12
0
class BabyProfile(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=20)
    born_weight = models.IntegerField(default=0)
    born_height = models.IntegerField(default=0)
    born_location = models.CharField(max_length=20, blank=True)
    birthday = models.DateTimeField()
    image = models.ImageField(upload_to='baby_profile_image', blank=True, default='profile_image/flower.png')
    image_thumbnail = ImageSpecField(
		source = 'image',
		processors = [Resize(700, 700)], # 처리할 작업 목룍
		format = 'JPEG',					# 최종 저장 포맷
		options = {'quality': 60})  		# 저장 옵션

    def __str__(self):
        return str(self.first_name)+str(self.last_name)
Example #13
0
def resize(img, width, height, size):
    def check_border(image, border, maxQ):
        image = ImageSpec(source=image)
        image.options = {'quality': border, 'optimize': True}
        image = image.generate()
        file_size = image.getbuffer().nbytes
        used_borders.add(border)
        result = file_size > int(size)
        if not result and maxQ < border:
            nonlocal max_in_size_quality
            max_in_size_quality = border
            nonlocal max_in_size_quality_img
            max_in_size_quality_img = image
        return result

    if width is None:
        width = img.width
    if height is None:
        height = img.height
    img = ImageSpec(source=img)
    img.processors = [Resize(int(width), int(height))]
    img.format = 'JPEG'
    img = img.generate()
    f_size = img.getbuffer().nbytes
    if size is not None and f_size > int(size):
        quality = 80
        upper_border = quality
        lower_border = quality // 2
        lower_from_last_iter = 0
        used_borders = set()
        max_in_size_quality = 0
        max_in_size_quality_img = BytesIO()
        for i in range(5):
            if lower_border not in used_borders:
                if check_border(img, lower_border, max_in_size_quality):
                    upper_border = lower_border
                    lower_border = (lower_border - lower_from_last_iter) // 2
                else:
                    lower_border = lower_border + (upper_border - lower_border) // 2
            if upper_border not in used_borders and check_border(img, upper_border, max_in_size_quality):
                upper_border = lower_border + (upper_border - lower_border) // 2
            lower_from_last_iter = lower_border
        if max_in_size_quality == 0:
            raise ValueError
        img = max_in_size_quality_img
    return img
Example #14
0
class News(models.Model):
    body = RichTextField(verbose_name=_('News|body'))
    carousel = models.BooleanField(default=False,
                                   verbose_name=_('News|carousel'))
    image = ProcessedImageField(upload_to='images/base',
                                processors=[Resize(800, 600, False)],
                                format='JPEG',
                                verbose_name=_('News|image'))
    cropped_image = ImageSpecField(source='image',
                                   processors=[Crop(400, 400)],
                                   format='JPEG')
    image_thumbnail = ImageSpecField(
        source='image',
        processors=[ResizeToCover(100, 100)],
        format='JPEG',
    )
    created_at = models.DateTimeField(auto_now_add=True,
                                      verbose_name=_('News|created'))
    updated_at = models.DateTimeField(auto_now=True,
                                      verbose_name=_('News|updated'))

    class Meta:
        verbose_name = _('News')
        verbose_name_plural = _('News|plural')

    def __str__(self):
        return str(self.id)

    def admin_image_tag(self):
        return u'<img src="%s" />' % self.image_thumbnail.url

    def admin_body(self):
        s = strip_tags(self.body)[:40]
        if len(strip_tags(self.body)) > 40:
            s += '...'
        return s

    admin_image_tag.allow_tags = True
    admin_body.allow_tags = True
    admin_body.short_description = _('News|body')
    admin_image_tag.short_description = _('News|Image')
Example #15
0
class UserProfile(models.Model):
    # From Django 2.0 on_delete is required
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    description = models.CharField(blank=True, max_length=100, default='')
    city = models.CharField(blank=True, max_length=100, default='')
    website = models.URLField(blank=True, default='')
    phone = models.CharField(blank=True, max_length=20, default='')
    image = models.ImageField(upload_to='profile_image', blank=True, default='profile_image/flower.png')
    image_thumbnail = ImageSpecField(
		source = 'image',
		processors = [Resize(700, 700)], # 처리할 작업 목룍
		format = 'JPEG',					# 최종 저장 포맷
		options = {'quality': 60})  		# 저장 옵션

    # Sodra_Sandby가 도시인 유저만 보이게 하고싶을때
    # Sodra_Sandby = UserProfileManager()
    objects = models.Manager()

    # user.userprofile 리턴값을 이름으로
    def __str__(self):
        return self.user.email
Example #16
0
class Benefit(models.Model):
    title = models.CharField(max_length=160, verbose_name=_('Название'))
    description = models.TextField(
        verbose_name=_('Описание'),
        blank=True,
        default='',
        validators=[validators.MaxLengthValidator(400)])
    icon = models.ImageField(
        verbose_name=_('Иконка'),
        upload_to='benefit_icons',
        help_text=_(
            'png, размер файла не более 1 мб, разрешение не более 1000*1000'))
    icon_thumbnail = ImageSpecField(source='icon',
                                    processors=[Resize(*ICON_THUMB_SIZE)])

    class Meta:
        verbose_name = _('Выгода')
        verbose_name_plural = _('Выгоды')

    def __str__(self):
        return self.title
Example #17
0
class Trainer(models.Model):
    """Model representing a trainer (not a specific class)"""
    writer = models.ForeignKey(settings.AUTH_USER_MODEL,
                               null=True,
                               blank=True,
                               on_delete=models.CASCADE,
                               verbose_name='작성자')
    name = models.CharField(max_length=10, verbose_name='이름')
    genretext = models.CharField(max_length=200, null=True)
    genre = models.ManyToManyField(Genre, blank=True, verbose_name='장르')
    address = models.CharField(max_length=40, null=True, verbose_name='지역')
    place = models.CharField(max_length=40, null=True, verbose_name='장소')
    summary = models.TextField(null=True, blank=True)
    tagtext = models.CharField(max_length=200, null=True, blank=True)
    hashtag = models.ManyToManyField(Hashtag, blank=True)
    # upload_files = models.FileField(upload_to=get_file_path, null=True, blank=True, verbose_name='파일')
    # filename = models.CharField(max_length=64, null=True, verbose_name='첨부파일명')
    image = ProcessedImageField(
        upload_to=get_profile_image_path,
        processors=[ResizeToFill(width=500, height=500, upscale=False)],
        null=True,
        blank=True,
        format='JPEG',
        options={'quality': 90},
        verbose_name="프로필 이미지")
    imagename = models.CharField(max_length=64,
                                 null=True,
                                 blank=True,
                                 verbose_name='이미지파일')

    # Certificate
    cert1, cert2, cert3, cert4, cert5, cert6, cert7, cert8, cert9, cert10 = [
        models.CharField(max_length=40, null=True, blank=True)
        for i in range(10)
    ]
    certimg1, certimg2, certimg3, certimg4, certimg5, certimg6, certimg7, certimg8, certimg9, certimg10 = [
        ProcessedImageField(
            upload_to=get_profile_image_path,
            processors=[Resize(width=500, height=None, upscale=False)],
            null=True,
            blank=True,
            format='JPEG',
            options={'quality': 90}) for i in range(10)
    ]
    # cert = [cert1, cert2, cert3, cert4, cert5, cert6, cert7, cert8, cert9, cert10]
    # certimg = [certimg1, certimg2, certimg3, certimg4, certimg5, certimg6, certimg7, certimg8, certimg9, certimg10]

    sns1, sns2, sns3, sns4, sns5 = [
        models.CharField(max_length=256, null=True, blank=True)
        for i in range(5)
    ]

    def hashtag_save(self):
        self.hashtag.set([])
        hashtags = re.findall(r'#(\w+)\b', self.tagtext)

        if not hashtags:
            return

        for tag in hashtags:
            tag, tag_created = Hashtag.objects.get_or_create(name=tag)
            self.hashtag.add(tag)

    def genre_save(self):
        self.genre.set([])
        genres = re.findall(r'(\w+)\b', self.genretext)

        if not genres:
            return

        for tag in genres:
            tag, tag_created = Genre.objects.get_or_create(name=tag)
            self.genre.add(tag)

    def __str__(self):
        """String for representing the Model object."""
        return self.name

    def get_absolute_url(self):
        """Returns the url to access a detail information for this trainer."""
        return reverse('trainer-detail', args=[str(self.id)])

    def display_genre(self):
        """Create a string for the Genre. This is required to display genre in Admin."""
        return ', '.join(genre.name for genre in self.genre.all()[:3])

    display_genre.short_description = 'Genre'

    class Meta:
        db_table = '트레이너'
        verbose_name = '트레이너'
        verbose_name_plural = '트레이너'

    def delete(self, *args, **kwargs):
        if self.image:
            os.remove(os.path.join(settings.MEDIA_ROOT, self.image.path))
        super(Trainer, self).delete(*args, **kwargs)
Example #18
0
class AbstractUser(AbstractBaseUser, PermissionsMixin):
    """ Institute user model """
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    username = models.CharField(_('Username'),
                                max_length=30,
                                blank=False,
                                null=False,
                                validators=[AlphaSpaceNumUnderscoreDot])
    mobile = models.CharField(_('Contact no'),
                              max_length=13,
                              blank=True,
                              null=False,
                              validators=[mobile_regex])
    date_joined = models.DateTimeField(_('date of joining'),
                                       default=timezone.now,
                                       blank=False)
    country_code = models.CharField(max_length=4, default='+91')
    iso = models.CharField(max_length=4, default='IN')
    is_active = models.BooleanField(_('active'), default=True)
    is_admin = models.BooleanField(_('admin'), default=False)
    is_staff = models.BooleanField(_('staff'), default=True)
    blocked = models.BooleanField(_('blocked'), default=False)
    image = ProcessedImageField(upload_to=upload_image,
                                blank=True,
                                null=True,
                                validators=[image_extension],
                                processors=[Resize(100, 100)],
                                format='JPEG',
                                options={'quality': 70})

    modified = models.DateTimeField(auto_now=True,
                                    auto_now_add=False,
                                    null=True)
    new_mobile = models.CharField(_('Contact no'),
                                  max_length=13,
                                  blank=True,
                                  null=False,
                                  validators=[mobile_regex])
    new_country_code = models.CharField(max_length=4, default='+91')
    new_iso = models.CharField(max_length=4, default='IN')
    otp = models.CharField(max_length=6, blank=True, null=False)
    age = models.IntegerField(blank=True, null=True)
    gender = models.CharField(max_length=30,
                              blank=True,
                              default='male',
                              choices=GENDER_CHOICE)
    initial_reg = models.BooleanField(default=False)
    final_reg = models.BooleanField(default=False)
    mobile_verify = models.BooleanField(default=False)
    location = models.CharField(max_length=200, blank=True, null=False)
    description = models.TextField(blank=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'mobile']

    class Meta:
        verbose_name = _('User')
        verbose_name_plural = _('Users')
        abstract = True

    def __str__(self):
        return str(self.email) + '(' + str(self.id) + ')'

    def get_short_name(self):
        return self.username

    def get_full_name(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return True

    def mobile_number(self):
        return self.country_code + self.mobile
Example #19
0
class Upsale(models.Model):
    ICON_THUMB_SIZE = (
        getattr(settings, 'UPSALE_ICON_SIZE', (100, 100))[0],
        getattr(settings, 'UPSALE_ICON_SIZE', (100, 100))[1]
    )
    IMAGE_THUMB_SIZE = (
        getattr(settings, 'UPSALE_IMAGE_SIZE', (180, 180))[0],
        getattr(settings, 'UPSALE_IMAGE_SIZE', (180, 180))[1]
    )
    slug = models.SlugField(verbose_name=_(u'Код'), unique=True)
    title = models.CharField(max_length=255, verbose_name=_(u'Название'))
    short_description = models.CharField(
        max_length=80,
        verbose_name=_(u'Короткое описание'),
        help_text=_(u'Отображается везде в интерфейсе рядом с названием')
    )
    description = models.CharField(
        max_length=400,
        verbose_name=_(u'Полное описание'),
        default='',
        blank=True,
        help_text=_(u'Отображается в раскрывающемся окне с подробной информацией по апсейлам')
    )
    additional_info = models.TextField(
        verbose_name=_(u'Дополнительная информация'),
        default='',
        blank=True,
        help_text=_(u'Дополнительная информация для отображения на странице продажи апсейлов. Возможно использование html тегов'))
    icon = models.ImageField(verbose_name=_(u'Иконка'), upload_to='upsale_icons')
    icon_thumbnail = ImageSpecField(source='icon', processors=[Resize(*ICON_THUMB_SIZE)])
    image = models.ImageField(verbose_name=_(u'Изображение услуги'), upload_to='upsale_images')
    image_thumbnail = ImageSpecField(source='image', processors=[Resize(*IMAGE_THUMB_SIZE)])
    max_per_session = models.PositiveSmallIntegerField(
        default=0,
        verbose_name=_(u'Максимальное количество услуг на 1 сессию'),
        help_text=_(u'0 - если нет ограничений. 1,2,3... - максимальное количество проданных апсейлов к 1 сессии курса')
    )
    price = models.PositiveIntegerField(verbose_name=_(u'Стоимость услуги'), default=0,
                                        help_text=_(u'0 - если бесплатно.'))
    discount_price = models.PositiveIntegerField(verbose_name=_(u'Стоимость услуги со скидкой'), blank=True, null=True,
                                                 help_text=_(u'Пусто - если нет скидки.'))
    days_to_buy = models.PositiveSmallIntegerField(
        verbose_name=_(u'В течение скольких дней с начала сессии возможно купить услугу на текущую сессию?'),
        blank=True, null=True
    )
    days_to_return = models.PositiveSmallIntegerField(
        verbose_name=_(u'За сколько дней до конца сессии прекращать возврат денег за услугу?'),
        blank=True, null=True
    )
    required = models.CommaSeparatedIntegerField(
        verbose_name=_(u'Необходимые услуги'),
        blank=True,
        null=True,
        max_length=100,
        help_text=_(u'Укажите id апсейлов, без которых текущий апсейл не может быть приобретен, через '
                    u'запятую без пробелов')
    )
    emails = models.CharField(
        verbose_name=_(u'Email ответственных за услугу'),
        blank=True,
        default='',
        max_length=255,
        help_text=_(u'Введите 1 или несколько адресов через запятую. По этим адресам будут '
                    u'приходить уведомления о записи на данную услугу с контактами пользователя.')
    )

    class Meta:
        verbose_name = _(u'Апсейл')
        verbose_name_plural = _(u'Апсейлы')

    def __unicode__(self):
        return u'%s - %s' % (self.slug, self.title)
class Banner(models.Model):
    orden = models.PositiveIntegerField()
    imagen = models.ImageField(upload_to='banners')
    home = ImageSpecField([Resize(920, 300)], source='imagen')