Exemplo n.º 1
0
class ImageModel(InfoModel):

    alt = StripCharField(
        verbose_name='alt',
        max_length=255,
        null=True,
        blank=True,
    )

    class Meta:
        abstract = True
        verbose_name = 'изображение'
        verbose_name_plural = 'изображения'

    def get_alt(self):
        return force_text(self.alt if bool(self.alt) else self.get_title())
Exemplo n.º 2
0
class Order(FromDBModel):

    name = StripCharField(
        verbose_name='имя',
        max_length=128,
        db_index=True,
    )

    phone = StripCharField(
        verbose_name='телефон',
        max_length=128,
        db_index=True,
    )

    sent_date = models.DateTimeField(
        verbose_name='дата',
        auto_now_add=True,
        db_index=True,
    )

    state = models.NullBooleanField(
        verbose_name='обратный звонок',
        db_index=True,
    )

    note = StripTextField(
        verbose_name='примечание',
        null=True,
        blank=True,
    )

    agent = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        limit_choices_to={'is_staff': True},
        related_name='+',
        verbose_name='агент',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
    )

    site = models.ForeignKey(
        Site,
        related_name='+',
        verbose_name='сайт',
        null=True,
        on_delete=models.CASCADE,
    )

    class Meta:
        db_table = CallbackConfig.label
        verbose_name = 'заказ'
        verbose_name_plural = 'заказы'
        ordering = (
            'state',
            '-sent_date',
            'site',
        )

    def __str__(self):
        return force_text(self.name)

    def save(self, *args, **kwargs):
        if self._state.adding:
            self.site = Site.objects.get_current()
        super(Order, self).save(*args, **kwargs)
Exemplo n.º 3
0
class Permit(WebLocalePageModel, PublishedModel):
    values = getattr(settings, 'PERMITS_AFFILIATES', [])
    OWNERS = {}
    OWNER_CHOICES = []
    for value in values:
        key = slugify(value)
        OWNERS[key] = value
        OWNER_CHOICES.append((
            key,
            value,
        ))

    owner = StripCharField(
        verbose_name='владелец',
        max_length=128,
        choices=OWNER_CHOICES,
        default=OWNER_CHOICES[0][0],
        db_index=True,
    )

    number = StripCharField(
        verbose_name='номер',
        max_length=128,
        null=True,
        blank=True,
    )

    provider = StripCharField(
        verbose_name='кем выдано',
        max_length=128,
    )

    issue_date = models.DateField(
        verbose_name='дата выдачи',
        null=True,
        blank=True,
    )

    onset_date = models.DateField(
        verbose_name='начало действия',
        null=True,
        blank=True,
    )

    end_date = models.DateField(
        verbose_name='окончание действия',
        null=True,
        blank=True,
    )

    note = StripTextField(
        verbose_name='примечания',
        null=True,
        blank=True,
    )

    alboms = GenericRelation(AlbomGeneric)

    class Meta:
        db_table = 'cck_permit'
        verbose_name = 'документ'
        verbose_name_plural = 'документы'
        ordering = (
            '-locale',
            'owner',
            'index',
        )
        unique_together = (
            'locale',
            'owner',
            'slug',
        ),

    @cached_property
    def generic(self):
        return self.alboms.all()

    @cached_property
    def cover(self):
        if self.generic:
            return self.generic[0].cover
        return None

    def get_absolute_url(self):
        lang = [self.locale] if len(settings.LANGUAGES) > 1 else []
        return reverse('permits:detail', args=lang + [self.owner, self.slug])

    get_absolute_url.short_description = 'URI'
    get_absolute_url.admin_order_field = 'slug'

    def get_owner_name(self):
        return self.OWNERS.get(self.owner, '<%s>' % self.owner)

    def get_owner_url(self):
        lang = [self.locale] if len(settings.LANGUAGES) > 1 else []
        return reverse('permits:list', args=lang + [self.owner])

    def clean(self):
        if not bool(self.title):
            self.title = '%s %s' % (strip_tags(self.name), self.number)
        super(Permit, self).clean()

        try:
            model = Permit.objects.get(
                locale=self.locale,
                owner=self.owner,
                slug=self.slug,
            )
            if model.pk != self.pk:
                raise ValidationError('Генерируется неуникальное значение URI')
        except Permit.DoesNotExist:
            pass
Exemplo n.º 4
0
class Object(WebLocalePageModel, PublishedModel):
    actual = models.BooleanField(
        verbose_name='в работе',
        default=False,
        db_index=True,
    )

    address = StripCharField(
        verbose_name='адрес',
        max_length=255,
    )

    longitude = models.FloatField(
        verbose_name='долгота',
        default=0,
        blank=True,
    )

    latitude = models.FloatField(
        verbose_name='широта',
        default=0,
        blank=True,
    )

    zoom = models.PositiveSmallIntegerField(
        verbose_name='зум',
        null=True,
        blank=True,
    )

    customer = StripCharField(
        verbose_name='заказчик',
        max_length=128,
    )

    developer = StripCharField(
        verbose_name='застройщик',
        max_length=128,
        null=True,
        blank=True,
    )

    start_date = models.DateField(
        verbose_name='начало работ',
        null=True,
        blank=True,
    )

    finish_date = models.DateField(
        verbose_name='окончание работ',
        null=True,
        blank=True,
    )

    note = StripTextField(
        verbose_name='примечания',
        null=True,
        blank=True,
    )

    activity = models.ManyToManyField(
        Activity,
        limit_choices_to={'published': True},
        db_table='cck_object_activity',
        verbose_name='деятельность',
        blank=True,
    )

    alboms = GenericRelation(AlbomGeneric)


    class Meta:
        db_table = 'cck_object'
        verbose_name = 'объект'
        verbose_name_plural = 'объекты'
        ordering = (
            '-locale',
            '-actual',
            'index',
        )
        unique_together = ('locale', 'slug',),


    @cached_property
    def activities(self):
        return self.activity.all()

    @cached_property
    def generic(self):
        return self.alboms.all()

    @cached_property
    def cover(self):
        if bool(self.generic):
            return self.generic[0].albom.cover
        return None

    def get_absolute_url(self):
        lang = [self.locale] if len(settings.LANGUAGES) > 1 else []
        return reverse('objects:detail', args=lang + [self.slug])

    get_absolute_url.short_description = 'URI'
    get_absolute_url.admin_order_field = 'slug'

    def clean(self):
        super(Object, self).clean()
        self.longitude = abs(self.longitude) if bool(self.longitude) else 0
        self.latitude = abs(self.latitude) if bool(self.latitude) else 0
        self.zoom = abs(self.zoom) if bool(self.zoom) else None
        try:
            model = Object.objects.get(
                locale=self.locale,
                slug=self.slug,
            )
            if model.pk != self.pk:
                raise ValidationError('Генерируется неуникальное значение URI')
        except Object.DoesNotExist:
            pass
Exemplo n.º 5
0
class Page(MPTTModel, WebLocalePageModel, PublishedModel):

    parent = TreeForeignKey(
        'self',
        limit_choices_to={'cluster': True},
        verbose_name='предок',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
    )

    cluster = models.BooleanField(
        verbose_name='кластер',
        default=False,
        db_index=True,
    )

    annotation = StripTextField(
        verbose_name='аннотация',
        null=True,
        blank=True,
    )

    content = StripTextField(verbose_name='содержание', )

    source = models.URLField(
        verbose_name='источник',
        max_length=255,
        null=True,
        blank=True,
    )

    layout = StripCharField(
        verbose_name='шаблон',
        max_length=255,
        null=True,
        blank=True,
    )

    publish = PublishMPTTManager()
    navigate = NavigateMPTTManager()

    class MPTTMeta:
        tree_id_attr = 'mptt_tree'
        level_attr = 'mptt_level'
        left_attr = 'mptt_left'
        right_attr = 'mptt_right'
        order_insertion_by = ['index']

    class Meta(WebLocalePageModel.Meta):
        db_table = ContentConfig.label
        verbose_name = 'страница'
        verbose_name_plural = 'страницы'
        ordering = (
            'mptt_tree',
            'mptt_left',
        )

    def get_absolute_url(self):
        return reverse('content:detail', args=[self.slug])

    get_absolute_url.short_description = 'URL'
    get_absolute_url.admin_order_field = 'slug'

    def get_layout(self):
        if bool(self.layout):
            return self.layout
        elif bool(self.parent):
            return self.parent.get_layout()
        return None

    get_layout.short_description = 'шаблон'

    def inherit(self):
        super(Page, self).clean()
        self.slug = '%s/%s' % (self.parent.slug, self.slug)
        self.save()

    def clean(self):
        super(Page, self).clean()
        if not self.is_leaf_node():
            self.cluster = True
        if bool(self.parent):
            if self.parent.pk == self.pk:
                raise ValidationError(
                    'Элемент не может быть потомком самому себе')
            self.slug = '%s/%s' % (self.parent.slug, self.slug)
        try:
            model = Page.objects.get(slug=self.slug)
            if model.pk != self.pk:
                raise ValidationError('Генерируется неуникальное значение URI')
        except Page.DoesNotExist:
            pass

    def save(self, *args, **kwargs):
        commit = adding = self._state.adding
        if not adding:
            for field in self._loaded_values:
                if self._loaded_values[field] != getattr(self, field):
                    commit = True
                    break
        if commit:
            super(Page, self).save(*args, **kwargs)
            if not adding and self._loaded_values['slug'] != self.slug:
                for model in self.get_children():
                    model.inherit()
            Page._tree_manager.rebuild()
Exemplo n.º 6
0
class Mail(FromDBModel):
    STATE_CHOICES = (
        ('0', 'Важное',),
        ('1', 'Прочитано',),
        ('2', 'Спам',),
    )

    name = StripCharField(
        verbose_name='имя',
        max_length=128,
        db_index=True,
    )

    email = StripCharField(
        max_length=128,
        db_index=True,
    )

    phone = StripCharField(
        verbose_name='телефон',
        max_length=128,
        null=True,
        blank=True,
    )

    subject = StripCharField(
        verbose_name='тема',
        max_length=128,
        null=True,
        blank=True,
        db_index=True,
    )

    message = StripTextField(
        verbose_name='сообщение',
    )

    sent_date = models.DateTimeField(
        verbose_name='дата',
        auto_now_add=True,
        db_index=True,
    )

    state = models.CharField(
        verbose_name='тип',
        max_length=1,
        choices=STATE_CHOICES,
        null=True,
        blank=True,
        db_index=True,
    )

    note = StripTextField(
        verbose_name='примечание',
        null=True,
        blank=True,
    )

    agent = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        limit_choices_to={'is_staff': True},
        related_name='+',
        verbose_name='агент',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
    )

    site = models.ForeignKey(
        Site,
        related_name='+',
        verbose_name='сайт',
        null=True,
        on_delete=models.CASCADE,
    )

    class Meta:
        db_table = PostboxConfig.label
        verbose_name = 'письмо'
        verbose_name_plural = 'письма'
        ordering = (
            'state',
            '-sent_date',
            'site',
        )

    def __str__(self):
        return force_text(self.name)

    def save(self, *args, **kwargs):
        if self._state.adding:
            self.site = Site.objects.get_current()
        super(Mail, self).save(*args, **kwargs)
Exemplo n.º 7
0
class Albom(ActiveModel, InfoModel):

    public = models.BooleanField(
        verbose_name='публичный',
        default=False,
        db_index=True,
    )

    type = StripCharField(
        verbose_name='тип',
        max_length=32,
        null=True,
        blank=True,
    )

    name = StripCharField(
        verbose_name='название',
        max_length=80,
        default='',
        db_index=True,
    )

    image = models.ManyToManyField(
        Image,
        through='AlbomThrough',
        through_fields=(
            'albom',
            'image',
        ),
        related_name='+',
        verbose_name='страницы',
    )

    class Meta(ActiveModel.Meta):
        verbose_name = 'альбом'
        verbose_name_plural = 'альбомы'

    @cached_property
    def images(self):
        return self.image.all()

    @cached_property
    def through(self):
        return self.albomthrough_set.all()

    @property
    def cover(self):
        if bool(self.through):
            return self.through[0]
        return None

    def __str__(self):
        return strip_tags(force_text(self.name))

    def get_title(self):
        return force_text(self.title if bool(self.title) else self.name)

    def get_thumb(self, *args, **kwargs):
        if bool(self.cover):
            return self.cover.get_thumb(*args, **kwargs)
        return '--'

    get_thumb.short_description = 'обложка'
    get_thumb.allow_tags = True

    def clean(self):
        self.type = self.type.lower()
        super(Albom, self).clean()
Exemplo n.º 8
0
class Image(ActiveModel, ImageModel):

    file = models.ImageField(
        verbose_name='загрузить',
        width_field='width',
        height_field='height',
        null=True,
        blank=True,
    )

    width = 0
    height = 0

    path = StripCharField(
        verbose_name='путь к файлам',
        max_length=64,
        null=True,
        blank=True,
    )

    type = StripCharField(
        verbose_name='тип',
        max_length=32,
        null=True,
        blank=True,
        db_index=True,
    )

    name = StripCharField(
        verbose_name='название',
        max_length=128,
        null=True,
        db_index=True,
    )

    class Meta(ImageModel.Meta):
        ordering = (
            '-active',
            'type',
            'name',
        )

    def __str__(self):
        return strip_tags(force_text(self.name))

    def get_title(self):
        return force_text(self.title if bool(self.title) else self.name)

    def get_thumb(self,
                  size=config['thumb_size'],
                  crop=config['thumb_crop'],
                  **kwargs):
        if bool(self.file):
            thumb = get_thumbnail(self.file, size, crop=crop)
            attrs = {
                'class': 'img-thumbnail hastip',
                'title': thumb.url,
                'src': thumb.url,
                'width': thumb.width,
                'height': thumb.height,
            }
            attrs.update(kwargs)
            attrs = format_html_join(' ', '{}="{}"',
                                     ((key, attrs[key]) for key in attrs))
            return format_html('<img {}>', attrs)
        return '--'

    get_thumb.short_description = 'файл'
    get_thumb.admin_order_field = 'file'
    get_thumb.allow_tags = True

    def get_thumb_link(self, *args, **kwargs):
        if bool(self.file):
            return format_html('<a href="{}{}" target="_blank">{}</a>',
                               settings.MEDIA_URL, self.file,
                               self.get_thumb(*args, **kwargs))
        return '--'

    get_thumb_link.short_description = 'файл'
    get_thumb_link.allow_tags = True

    def clean(self):
        self.type = self.type.lower()
        super(Image, self).clean()