Exemple #1
0
class Two_column(models.Model):
    class Meta:
        verbose_name = "Двухколоночный"
        abstract = True

    title = models.CharField(max_length=150, verbose_name='Название')
    picture1 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 1")
    key1 = models.CharField(max_length=150,
                            verbose_name='Подпись под картинкой 1',
                            blank=True,
                            null=True)
    text1 = models.TextField(verbose_name="Текст 1", max_length=600)

    picture2 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 2")
    key2 = models.CharField(max_length=150,
                            verbose_name='Подпись под картинкой 2',
                            null=True,
                            blank=True)
    text2 = models.TextField(verbose_name="Текст 2", max_length=600)

    @property
    def get_img(self):
        return join(settings.MEDIA_URL,
                    str(self.picture1.file)), join(settings.MEDIA_URL,
                                                   str(self.picture2.file))

    def render(self):
        return render_to_string('widget/two-column/widgets-page.html',
                                {'two': self})

    def save(
        self, **kwargs
    ):  ############################################################################################
        super().save(**kwargs)
        content = self.title + " " + self.key1 + " " + self.text1 + " " + self.key2 + " " + self.text2
        content = " ".join(findall(r'[\w ]+', content))
        for w in content.lower().split():
            find_pages = Search.objects.filter(word=w)
            if find_pages:
                find_pages[0].pages.add(Page.objects.get(id=self.parent_id))
                find_pages[0].save()
            else:
                s = Search(word=w)
                s.save()
                s.pages.add(Page.objects.get(id=self.parent_id))
                s.save()
Exemple #2
0
    def initialize_type(cls):
        if 'feincms.module.medialibrary' not in django_settings.INSTALLED_APPS:
            raise ImproperlyConfigured('You have to add \'feincms.module.medialibrary\' to your INSTALLED_APPS before creating a %s' % cls.__name__)

        cls.add_to_class('video_mediafile', MediaFileForeignKey(MediaFile, limit_choices_to={'type':VIDEO_TYPE}, verbose_name=_('video'),
            related_name='%s_%s_set' % (cls._meta.app_label, cls._meta.module_name),
            ))
        cls.add_to_class('preview_mediafile', MediaFileForeignKey(MediaFile, limit_choices_to={'type':IMAGE_TYPE}, verbose_name=_('preview image'),
            related_name='%s_%s_preview_set' % (cls._meta.app_label, cls._meta.module_name),
            null=True,
            ))
Exemple #3
0
    def handle_model(self):
        self.model.add_to_class(
            'category',
            TreeManyToManyField(
                Category,
                null=False,
                blank=False,
                related_name="%(app_label)s_%(class)s_category",
                verbose_name='Раздел-категория-тег'))

        self.model.add_to_class(
            'mediafile',
            MediaFileForeignKey(MediaFile,
                                on_delete=models.SET_NULL,
                                related_name='+',
                                null=True,
                                verbose_name='Картинка'))

        self.model.add_to_class('name_category', property(name_category))
        self.model.add_to_class(
            'url_img',
            property(
                lambda x: join(settings.MEDIA_URL, str(x.mediafile.file))))
        self.model.add_to_class('stars',
                                models.PositiveIntegerField(default=0))
        self.model.add_to_class('count_for_r',
                                models.PositiveIntegerField(default=0))
        self.model.add_to_class(
            'raiting', models.FloatField(default=0, verbose_name='Рейтинг'))
Exemple #4
0
class Block(models.Model):
    class Meta():
        verbose_name = 'Блок главной страницы'
        verbose_name_plural = 'Блоки главной страницы'

    title = models.CharField(max_length=100, verbose_name="Название блока")
    slug = models.SlugField(verbose_name="Слаг")
    name_button = models.CharField(max_length=100,
                                   verbose_name="Название кнопки")
    text = models.TextField(verbose_name="Текст")
    picture = MediaFileForeignKey(MediaFile,
                                  related_name='+',
                                  on_delete=models.SET_NULL,
                                  null=True,
                                  verbose_name="Картинка")
    categories = models.ManyToManyField(Category,
                                        verbose_name="Раздел-категория-тег")
    pages = models.ManyToManyField(Page, verbose_name="Статьи")

    def __str__(self):
        return self.title

    @property
    def get_img(self):
        return join(settings.MEDIA_URL, str(self.picture.file))
Exemple #5
0
 def handle_model(self):
     self.model.add_to_class(
         'excerpt_image',
         MediaFileForeignKey(MediaFile,
                             verbose_name=_('image'),
                             blank=True,
                             null=True,
                             related_name='+'))
     self.model.add_to_class('excerpt_text',
                             models.TextField(_('text'), blank=True))
Exemple #6
0
class Category(MPTTModel):
    class Meta():
        db_table = 'category'
        verbose_name = 'Раздел-категория-тег'
        verbose_name_plural = 'Раздел-категория-тег'
        ordering = ('tree_id', 'level')

    class MPTTMeta:
        order_insertion_by = ['title']

    title = models.CharField(max_length=50,
                             unique=False,
                             verbose_name='Название')
    slug = models.SlugField(verbose_name="Слаг")
    flag = models.BooleanField(
        verbose_name="Стадия разработки",
        default=False,
        help_text="Страницы будут не доступны для пользователя")
    parent = TreeForeignKey('self',
                            on_delete=models.CASCADE,
                            null=True,
                            blank=True,
                            related_name='children',
                            verbose_name='Родитель')
    mediafile = MediaFileForeignKey(MediaFile,
                                    related_name='+',
                                    null=True,
                                    blank=True,
                                    on_delete=models.SET_NULL,
                                    verbose_name='Картинка')

    def __str__(self):
        return self.title

    @property
    def get_url(self):
        all_slugs = []
        id = self.id
        while self:
            all_slugs.append(str(self.slug))
            self = self.parent
        return '/'.join(all_slugs[::-1]) + '|' + str(id)

    @property
    def url_img(self):
        return join(settings.MEDIA_URL, str(self.mediafile.file))

    @property
    def get_img(self):
        if self.mediafile:
            return format_html(f"<img src='{self.url_img}' width='70px'>")
        return None
Exemple #7
0
class Articles(models.Model):
    class Meta:
        verbose_name = 'Статья'
        verbose_name_plural = 'Статьи'

    category = models.ManyToManyField('Main_Cat')
    is_active = models.BooleanField(default=True)
    title = models.CharField(
        verbose_name='Название',
        max_length=256,
    )
    picture = MediaFileForeignKey(
        MediaFile,
        on_delete=models.SET_NULL,
        verbose_name='Картинка',
        null=True,
        blank=True,
    )
    pic_text = models.CharField(
        verbose_name='Подпись катринки',
        max_length=256,
        null=True,
        blank=True
    )
    text = models.TextField(
        verbose_name='основной текст',
    )
    points = models.TextField(
        verbose_name='Пункты/список',
        blank=True,
        null=True,
        help_text='<li> текст пункта </li>'
    )
    link = models.ManyToManyField(
        'Link',
        null=True,
        blank=True,
        verbose_name='Ссылка',
        help_text='Можно добавить ардесс-ссылку на внешний источник или'
                  ' на статью.'
    )


    def get_img(self):
        if not self.picture:
            return None
        else:
            return join(settings.MEDIA_URL, str(self.picture.file))

    def __str__(self):
        return self.title
Exemple #8
0
class ArticleContent(models.Model):
    feincms_item_editor_inline = ArticleContentInline

    title = models.CharField(_('title'), max_length=200, blank=True)
    text = models.TextField(_('text'), blank=True)
    link = models.URLField(verify_exists=False, blank=True)
    link_text = models.CharField(max_length=50, blank=True)
    mediafile = MediaFileForeignKey(MediaFile, blank=True, null=True)

    class Meta:
        abstract = True
        verbose_name = "Article content"

    def render(self, **kwargs):
        return render_to_string([
            "content/article/%s.html" % self.region,
            "content/article/default.html",
        ], {'content': self})
class Help_for_addicts_links(models.Model):
    class Meta:
        db_table = 'Помощь наркозависимым'
        verbose_name = 'Сcылки для "Помощь наркозависимым"'
        verbose_name_plural = 'Сcылки для "Помощь наркозависимым"'

    url = models.URLField(verbose_name='Ссылка')
    title = models.CharField(max_length=25, verbose_name='название ссылки')
    mediafile = MediaFileForeignKey(MediaFile,
                                    related_name='+',
                                    null=True,
                                    on_delete=models.SET_NULL,
                                    verbose_name='Картинка')

    def __str__(self):
        return self.title

    @property
    def get_img(self):
        return join(settings.MEDIA_URL, str(self.mediafile.file))
class Network_security_links(models.Model):
    class Meta:
        db_table = 'Безопасность в сети'
        verbose_name = 'Ссылки для "Безопасность в сети"'
        verbose_name_plural = 'Ссылки для "Безопасность в сети"'

    url = models.URLField(verbose_name='Ссылка')
    title = models.CharField(max_length=25, verbose_name='название ссылки')
    mediafile = MediaFileForeignKey(MediaFile,
                                    related_name='+',
                                    null=True,
                                    on_delete=models.SET_NULL,
                                    verbose_name='Картинка')

    def __str__(self):
        return self.title

    @property
    def get_img(self):
        return join(settings.MEDIA_URL, str(self.mediafile.file))
Exemple #11
0
class PageTeaserContent(models.Model):
    """
    Contenttype for teasering another page.
    The user can specify the page, an image and a title.
    The image and the title attribute are optional.
    """
    feincms_item_editor_inline = PageTeaserInline

    page = models.ForeignKey(Page, verbose_name=_('page'), related_name='+')
    mediafile = MediaFileForeignKey(MediaFile,
                                    verbose_name=_('mediafile'),
                                    related_name='+',
                                    limit_choices_to={'type': 'image'})
    title = models.CharField(_('title'), max_length=100, blank=True)

    class Meta:
        abstract = True
        verbose_name = _('page teaser')
        verbose_name_plural = _('page teasers')

    @classmethod
    def get_queryset(cls, filter_args):
        return cls.objects.filter(filter_args).select_related(
            'parent', 'page', 'mediafile')

    def render(self, **kwargs):
        return render_to_string('content/pageteaser/default.html', {
            'content': self,
        })

    def save(self, *args, **kwargs):
        if not self.title:
            self.title = self.page.title
        if not self.mediafile:
            try:
                self.mediafile = self.page.content.all_of_type(
                    MediaFileContent)[0]
            except IndexError:
                pass
        super(PageTeaserContent, self).save(*args, **kwargs)
Exemple #12
0
class QuizQuestion(models.Model):
    feincms_item_editor_inline = MediaFileInline
    image = MediaFileForeignKey(MediaFile,
                                limit_choices_to=models.Q(
                                    type='image', categories__title='en'),
                                blank=True,
                                null=True)
    question = models.TextField(help_text='HTML is allowed.')
    correct_feedback = models.TextField(help_text='HTML is allowed.')
    incorrect_feedback = models.TextField(help_text='HTML is allowed.')
    partly_correct_feedback = models.TextField(help_text='HTML is allowed.')
    _l10n_fields = [
        'question', 'correct_feedback', 'incorrect_feedback',
        'partly_correct_feedback'
    ]

    class Meta:
        abstract = True

    def render(self, **kwargs):
        return render_to_string('includes/quizquestion.html',
                                {'question': self})
class Partners(models.Model):
    class Meta():
        verbose_name = "Партнер"
        verbose_name_plural = "Партнеры"

    mediafile = MediaFileForeignKey(MediaFile,
                                    related_name='+',
                                    null=True,
                                    on_delete=models.SET_NULL,
                                    verbose_name='Картинка')
    link = models.CharField(max_length=100, verbose_name='Ссылка')

    def __str__(self):
        return self.link

    @property
    def url_img(self):
        return join(settings.MEDIA_URL, str(self.mediafile.file))

    @property
    def get_img(self):
        return format_html(f"<img src='{self.url_img}' width='70px'>")
Exemple #14
0
class ImageParagraphEntry(models.Model):
    feincms_item_editor_inline = MediaFileInline
    image = MediaFileForeignKey(MediaFile)
    alt = models.CharField(max_length=255, blank=True, default='')
    title = models.CharField(max_length=255)
    subheader_2 = models.CharField(max_length=255, blank=True)
    subheader_3 = models.CharField(max_length=255, blank=True)
    text = models.TextField(help_text='HTML is allowed.')
    _l10n_fields = ['alt', 'title', 'text', 'subheader_2', 'subheader_3']

    class Meta:
        abstract = True

    def render(self, **kwargs):
        return render_to_string(
            'includes/imageparagraph.html', {
                'alt': _(self.alt) if self.alt else '',
                'title': _(self.title),
                'text': Markup(_(self.text)),
                'subheader_2': _(self.subheader_2) if self.subheader_2 else '',
                'subheader_3': _(self.subheader_3) if self.subheader_3 else '',
                'image': self.image,
            })
Exemple #15
0
class Block(models.Model):  # Todo REFACTOR
    is_active = models.BooleanField(default=True)
    title = models.CharField(max_length=100, verbose_name="Название блока")
    slug = models.SlugField(verbose_name="Слаг")
    name_button = models.CharField(
        max_length=100,
        verbose_name="Название кнопки",
        null=True,
        blank=True
    )
    text = models.TextField(verbose_name="Текст блока")
    picture = MediaFileForeignKey(MediaFile,
                                  on_delete=models.SET_NULL,
                                  null=True,
                                  blank=True,
                                  verbose_name="Картинка")
    # categories = models.ManyToManyField(Category, verbose_name="Раздел-категория-тег")
    pages = models.ManyToManyField(Page, verbose_name="Статьи")

    def get_img(self):
        if not self.picture:
            return None
        else:
            return join(settings.MEDIA_URL, str(self.picture.file))
Exemple #16
0
class Single_column(models.Model):
    class Meta:
        verbose_name = "Одноколоночный"
        abstract = True

    title = models.CharField(verbose_name='подпись Виджета', max_length=150)
    picture = MediaFileForeignKey(MediaFile,
                                  related_name='+',
                                  null=True,
                                  on_delete=models.SET_NULL,
                                  verbose_name="Картинка")
    under_img = models.CharField(max_length=150,
                                 verbose_name="подпись картинки",
                                 blank=True,
                                 null=True)
    text = models.TextField(verbose_name='основной текст',
                            default='<p></p>',
                            help_text='''&ltp&gt &lt/p&gt-Тег для выделения
                             &lti&gt &lt/i&gt-курсив &ltb&gt &lt/b&gt-Жирный шрифт '''
                            )

    title2 = models.CharField(max_length=150,
                              verbose_name='заголовок пунктов',
                              null=True,
                              blank=True)
    point = models.TextField(
        verbose_name='пункты',
        default='<li></li>',
        help_text='&ltli&gt &lt/li&gt -Тег для установки точки',
        null=True,
        blank=True)

    def render(self):
        return render_to_string(
            'widget/single-column/widgets-page.html', {
                'widget': self,
                'text': mark_safe(self.text),
                'point': mark_safe(self.point)
            })

    @property
    def get_img(self):
        return join(settings.MEDIA_URL, str(self.picture.file))

    def save(
        self, **kwargs
    ):  ############################################################################################
        super().save(**kwargs)
        content = self.title + " " + self.under_img + " " + self.text.replace(
            '<p>', '').replace('</p>', '') + " "
        content += self.title2 + " " + self.point.replace('<li>', '').replace(
            '</li>', '')
        content = " ".join(findall(r'[\w ]+', content))
        for w in content.lower().split():
            find_pages = Search.objects.filter(word=w)
            if find_pages:
                find_pages[0].pages.add(Page.objects.get(id=self.parent_id))
                find_pages[0].save()
            else:
                s = Search(word=w)
                s.save()
                s.pages.add(Page.objects.get(id=self.parent_id))
                s.save()
Exemple #17
0
class SectionContent(models.Model):
    """
    Title, media file and rich text fields in one content block.
    """

    feincms_item_editor_inline = SectionContentInline
    feincms_item_editor_context_processors = (
        lambda x: settings.FEINCMS_RICHTEXT_INIT_CONTEXT, )
    feincms_item_editor_includes = {
        'head': [settings.FEINCMS_RICHTEXT_INIT_TEMPLATE],
    }

    title = models.CharField(_('title'), max_length=200, blank=True)
    richtext = RichTextField(_('text'), blank=True)
    mediafile = MediaFileForeignKey(MediaFile,
                                    on_delete=models.CASCADE,
                                    verbose_name=_('media file'),
                                    related_name='+',
                                    blank=True,
                                    null=True)

    class Meta:
        abstract = True
        verbose_name = _('section')
        verbose_name_plural = _('sections')

    @classmethod
    def initialize_type(cls, TYPE_CHOICES=None, cleanse=None):
        if 'feincms.module.medialibrary' not in django_settings.INSTALLED_APPS:
            raise ImproperlyConfigured(
                'You have to add \'feincms.module.medialibrary\' to your'
                ' INSTALLED_APPS before creating a %s' % cls.__name__)

        if TYPE_CHOICES is None:
            raise ImproperlyConfigured(
                'You need to set TYPE_CHOICES when creating a'
                ' %s' % cls.__name__)

        cls.add_to_class(
            'type',
            models.CharField(_('type'),
                             max_length=10,
                             choices=TYPE_CHOICES,
                             default=TYPE_CHOICES[0][0]))

        if cleanse:
            cls.cleanse = cleanse

    @classmethod
    def get_queryset(cls, filter_args):
        # Explicitly add nullable FK mediafile to minimize the DB query count
        return cls.objects.select_related('parent',
                                          'mediafile').filter(filter_args)

    def render(self, **kwargs):
        if self.mediafile:
            mediafile_type = self.mediafile.type
        else:
            mediafile_type = 'nomedia'

        return ct_render_to_string(
            [
                'content/section/%s_%s.html' % (mediafile_type, self.type),
                'content/section/%s.html' % mediafile_type,
                'content/section/%s.html' % self.type,
                'content/section/default.html',
            ],
            {'content': self},
            request=kwargs.get('request'),
            context=kwargs.get('context'),
        )

    def save(self, *args, **kwargs):
        if getattr(self, 'cleanse', None):
            try:
                # Passes the rich text content as first argument because
                # the passed callable has been converted into a bound method
                self.richtext = self.cleanse(self.richtext)
            except TypeError:
                # Call the original callable, does not pass the rich richtext
                # content instance along
                self.richtext = self.cleanse.im_func(self.richtext)

        super(SectionContent, self).save(*args, **kwargs)

    save.alters_data = True
Exemple #18
0
class Three_column(models.Model):
    class Meta:
        verbose_name = "Трехколоночный"
        abstract = True

    title = models.CharField(max_length=70, verbose_name='Название')

    picture1 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 1")
    key1 = models.CharField(max_length=70,
                            verbose_name='Подпись 1',
                            null=True,
                            blank=True)

    picture2 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 2")
    key2 = models.CharField(max_length=70,
                            verbose_name='Подпись 2',
                            null=True,
                            blank=True)

    picture3 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 3")
    key3 = models.CharField(max_length=70,
                            verbose_name='Подпись 3',
                            null=True,
                            blank=True)

    picture4 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 4")
    key4 = models.CharField(max_length=70,
                            verbose_name='Подпись 4',
                            null=True,
                            blank=True)

    picture5 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 5")
    key5 = models.CharField(max_length=70,
                            verbose_name='Подпись 5',
                            null=True,
                            blank=True)

    picture6 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 6")
    key6 = models.CharField(max_length=70,
                            verbose_name='Подпись 6',
                            null=True,
                            blank=True)

    picture7 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 7")
    key7 = models.CharField(max_length=70,
                            verbose_name='Подпись 7',
                            null=True,
                            blank=True)

    @property
    def get_img(self):
        imgs = [
            join(settings.MEDIA_URL, str(i.file)) for i in [
                self.picture1, self.picture2, self.picture3, self.picture4,
                self.picture5, self.picture6, self.picture7
            ] if i
        ]
        return imgs

    def render(self):
        return render_to_string('widget/three-column/widgets-page.html',
                                {'obj': self})

    def save(
        self, **kwargs
    ):  ############################################################################################
        super().save(**kwargs)
        content = self.title + " "
        if self.key1:
            content += self.key1 + " "
        if self.key2:
            content += self.key2 + " "
        if self.key3:
            content += self.key3 + " "
        if self.key4:
            content += self.key4 + " "
        if self.key5:
            content += self.key5 + " "
        if self.key6:
            content += self.key6 + " "
        if self.key7:
            content += self.key7
        content = " ".join(findall(r'[\w ]+', content))
        for w in content.lower().split():
            find_pages = Search.objects.filter(word=w)
            if find_pages:
                find_pages[0].pages.add(Page.objects.get(id=self.parent_id))
                find_pages[0].save()
            else:
                s = Search(word=w)
                s.save()
                s.pages.add(Page.objects.get(id=self.parent_id))
                s.save()
Exemple #19
0
class Event(models.Model, translations.TranslatedObjectMixin):
    """
    Stores an event entry. An event needs to have at least a start date. There
    are 3 possible types of events:

    * One day events (only start date is given)
    * Multi day events (start and end date is given)
    * Timed event (start date and time and end date and time are given)

    Title, slug and description are translateable trough
    :model:`feincms_agenda.models.EventTranslation`
    """
    def __init__(self, *args, **kwargs):
        super(Event, self).__init__(*args, **kwargs)
        self.cleanse = getattr(settings, 'EVENT_CLEANSE', False)
        cm = getattr(settings, 'CLEANSE_MODULE', None)
        if cm:
            try:
                # TODO importlib or something else; or reuse the
                # richtext field from FeinCMS and add cleansing there
                self.cleanse_module = __import__(cm, fromlist=True)
            except (ValueError, ImportError):
                raise ImproperlyConfigured(
                    'There was an error importing your %s cleanse_module!' %
                    (self.__name__, ))
        else:
            self.cleanse_module = cleanse

    active = models.BooleanField(_('Active'))

    start_date = models.DateField(_('Start date'))
    start_time = models.TimeField(
        _('Start time'),
        blank=True,
        null=True,
        help_text=_('leave blank for full day event'))
    end_date = models.DateField(_('End date'),
                                blank=True,
                                null=True,
                                help_text=_('leave blank for one day event'))
    end_time = models.TimeField(_('End time'),
                                blank=True,
                                null=True,
                                help_text=_('leave blank for full day events'))

    type = models.CharField(_('Type'),
                            max_length=10,
                            help_text=_('Cachefield for the computed type'),
                            editable=False,
                            choices=(
                                ('oneday', _('One day event')),
                                ('multiday', _('Multi day event')),
                                ('timed', _('Timed event')),
                                ('timedm', _('Timed event multiple days')),
                            ))

    image = MediaFileForeignKey(MediaFile, blank=True, null=True)

    feincms_page = models.ForeignKey(
        Page,
        blank=True,
        null=True,
        help_text=_('FeinCMS Page with additional infos'))

    address = models.CharField(_('Address'),
                               max_length=150,
                               blank=True,
                               null=True)
    country = CountryField(blank=True, null=True)

    categories = models.ManyToManyField(Category,
                                        blank=True,
                                        null=True,
                                        verbose_name=_('categories'))

    objects = EventManager()

    class Meta:
        ordering = ['start_date']
        verbose_name = _('event')
        verbose_name_plural = _('events')

    def get_absolute_url(self):
        return app_reverse('agenda_event_detail',
                           'feincms_agenda.urls',
                           args=(),
                           kwargs={'slug': self.translation.slug})

    @property
    def datetime(self):
        """ datetime property for legacy support """
        return self.start_date

    def clean(self):
        """ tries to find the type of the event and stores it in the type field.
            in this process, it guesses possible forgotten values
        """
        if self.start_time and self.end_date and not self.end_time:
            self.end_time = time(23, 59, 59)
        if self.end_time and not self.start_time:
            self.start_time = time(0)
        if self.start_time and self.end_time and not self.end_date:
            if self.end_time > self.start_time:
                self.end_date = self.start_date
            else:
                self.end_date = self.start_date + timedelta(days=1)

        if not self.start_time and not self.end_date and not self.end_time:
            self.end_date = self.start_date
            self.type = 'oneday'
        elif (self.start_date
              == self.end_date) and not (self.start_time or self.end_time):
            self.type = 'oneday'
        elif self.start_time:
            if self.start_date == self.end_date:
                self.type = 'timed'
            else:
                self.type = 'timedm'
        elif self.end_date and not self.start_time:
            self.type = 'multiday'

        # an event can't end before it starts
        if self.end_date < self.start_date:
            raise ValidationError(
                _('The Event cannot end before start (Start date <= End date)')
            )
        if (self.end_date
                == self.start_date) and (self.end_time < self.start_time):
            raise ValidationError(
                _('The Event cannot end before start (Start time <= End time)')
            )
Exemple #20
0
class Slider(models.Model):
    class Meta:
        verbose_name = "Слайдер для малышей"
        abstract = True

    title = models.CharField(max_length=150, verbose_name='название')

    picture1 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 1")
    key1 = models.CharField(max_length=70,
                            verbose_name='Заголовок под картинкой',
                            null=True,
                            blank=True)
    for_picture1 = models.CharField(max_length=70,
                                    null=True,
                                    blank=True,
                                    verbose_name='подпись под картинкой 1')
    text1 = models.TextField(
        verbose_name='Текст 1',
        null=True,
        blank=True,
        max_length=500,
        help_text=
        "слайд счиается валидным если у него заполнены поля:\n Картинка, заголовок под картинкой и сам ткст - в противном случае этот слайд показан не будет"
    )

    picture2 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 2")
    key2 = models.CharField(max_length=70,
                            verbose_name='Заголовок под картинкой',
                            null=True,
                            blank=True)
    for_picture2 = models.CharField(max_length=70,
                                    null=True,
                                    blank=True,
                                    verbose_name='подпись под картинкой 2')
    text2 = models.TextField(
        verbose_name='Текст 2',
        null=True,
        blank=True,
        max_length=500,
        help_text=
        "слайд счиается валидным если у него заполнены поля:\n Картинка, заголовок под картинкой и сам ткст - в противном случае этот слайд показан не будет"
    )

    picture3 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 3")
    key3 = models.CharField(max_length=70,
                            verbose_name='Заголовок под картинкой',
                            null=True,
                            blank=True)
    for_picture3 = models.CharField(max_length=70,
                                    null=True,
                                    blank=True,
                                    verbose_name='подпись под картинкой 3')
    text3 = models.TextField(
        verbose_name='Текст 3',
        null=True,
        blank=True,
        max_length=500,
        help_text=
        "слайд счиается валидным если у него заполнены поля:\n Картинка, заголовок под картинкой и сам ткст - в противном случае этот слайд показан не будет"
    )

    picture4 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 4")
    key4 = models.CharField(max_length=70,
                            verbose_name='Заголовок под картинкой',
                            null=True,
                            blank=True)
    for_picture4 = models.CharField(max_length=70,
                                    null=True,
                                    blank=True,
                                    verbose_name='подпись под картинкой 4')
    text4 = models.TextField(
        verbose_name='Текст 4',
        null=True,
        blank=True,
        max_length=500,
        help_text=
        "слайд счиается валидным если у него заполнены поля:\n Картинка, заголовок под картинкой и сам ткст - в противном случае этот слайд показан не будет"
    )

    picture5 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 5")
    key5 = models.CharField(max_length=70,
                            verbose_name='Заголовок под картинкой',
                            null=True,
                            blank=True)
    for_picture5 = models.CharField(max_length=70,
                                    null=True,
                                    blank=True,
                                    verbose_name='подпись под картинкой 5')
    text5 = models.TextField(
        verbose_name='Текст 5',
        null=True,
        blank=True,
        max_length=500,
        help_text=
        "слайд счиается валидным если у него заполнены поля:\n Картинка, заголовок под картинкой и сам ткст - в противном случае этот слайд показан не будет"
    )

    picture6 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 6")
    key6 = models.CharField(max_length=70,
                            verbose_name='Заголовок под картинкой',
                            null=True,
                            blank=True)
    for_picture6 = models.CharField(max_length=70,
                                    null=True,
                                    blank=True,
                                    verbose_name='подпись под картинкой 6')
    text6 = models.TextField(
        verbose_name='Текст 6',
        null=True,
        blank=True,
        max_length=500,
        help_text=
        "слайд счиается валидным если у него заполнены поля:\n Картинка, заголовок под картинкой и сам ткст - в противном случае этот слайд показан не будет"
    )

    picture7 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 7")
    key7 = models.CharField(max_length=70,
                            verbose_name='Заголовок под картинкой',
                            null=True,
                            blank=True)
    for_picture7 = models.CharField(max_length=70,
                                    null=True,
                                    blank=True,
                                    verbose_name='подпись под картинкой 7')
    text7 = models.TextField(
        verbose_name='Текст 7',
        null=True,
        blank=True,
        max_length=500,
        help_text=
        "слайд счиается валидным если у него заполнены поля:\n Картинка, заголовок под картинкой и сам ткст - в противном случае этот слайд показан не будет"
    )

    picture8 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 8")
    key8 = models.CharField(max_length=70,
                            verbose_name='Заголовок под картинкой',
                            null=True,
                            blank=True)
    for_picture8 = models.CharField(max_length=70,
                                    null=True,
                                    blank=True,
                                    verbose_name='подпись под картинкой 8')
    text8 = models.TextField(
        verbose_name='Текст 8',
        null=True,
        blank=True,
        max_length=500,
        help_text=
        "слайд счиается валидным если у него заполнены поля:\n Картинка, заголовок под картинкой и сам ткст - в противном случае этот слайд показан не будет"
    )

    picture9 = MediaFileForeignKey(MediaFile,
                                   related_name='+',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   verbose_name="Картинка 9")
    key9 = models.CharField(max_length=70,
                            verbose_name='Заголовок под картинкой',
                            null=True,
                            blank=True)
    for_picture9 = models.CharField(max_length=70,
                                    null=True,
                                    blank=True,
                                    verbose_name='подпись под картинкой 9')
    text9 = models.TextField(
        verbose_name='Текст 9',
        null=True,
        blank=True,
        max_length=500,
        help_text=
        "слайд счиается валидным если у него заполнены поля:\n Картинка, заголовок под картинкой и сам ткст - в противном случае этот слайд показан не будет"
    )

    picture10 = MediaFileForeignKey(MediaFile,
                                    related_name='+',
                                    null=True,
                                    blank=True,
                                    on_delete=models.SET_NULL,
                                    verbose_name="Картинка 10")
    key10 = models.CharField(max_length=70,
                             verbose_name='Заголовок под картинкой',
                             null=True,
                             blank=True)
    for_picture10 = models.CharField(max_length=70,
                                     null=True,
                                     blank=True,
                                     verbose_name='подпись под картинкой 10')
    text10 = models.TextField(
        verbose_name='Текст 10',
        null=True,
        blank=True,
        max_length=500,
        help_text=
        "слайд счиается валидным если у него заполнены поля:\n Картинка, заголовок под картинкой и сам ткст - в противном случае этот слайд показан не будет"
    )

    @property
    def valid_slides(self):
        l = [
            i for i in
            [(self.picture1, self.for_picture1, self.key1, self.text1
              ), (self.picture2, self.for_picture2, self.key2, self.text2
                  ), (self.picture3, self.for_picture3, self.key3, self.text3),
             (self.picture4, self.for_picture4, self.key4, self.text4
              ), (self.picture5, self.for_picture5, self.key5, self.text5
                  ), (self.picture6, self.for_picture6, self.key6, self.text6),
             (self.picture7, self.for_picture7, self.key7, self.text7
              ), (self.picture8, self.for_picture8, self.key8, self.text8
                  ), (self.picture9, self.for_picture9, self.key9, self.text9),
             (self.picture10, self.for_picture10, self.key10, self.text10)]
            if i[0] and i[2] and i[3]
        ]
        return l

    @property
    def get_img(self):
        l = self.valid_slides
        #imgs = [join(settings.MEDIA_URL, str(i[0].file)) for i in l]
        imgs = [(join(settings.MEDIA_URL, str(i[0].file)), i[1], i[2], i[3])
                for i in l]
        return imgs

    def render(self):
        return render_to_string('widget/slider/widget-page.html',
                                {'slider': self})

    def save(
        self, **kwargs
    ):  ############################################################################################
        super().save(**kwargs)
        content = self.title + " "
        if self.text1:
            content += self.text1 + " "
        if self.text1:
            content += self.text2 + " "
        if self.text1:
            content += self.text3 + " "
        if self.text1:
            content += self.text4 + " "
        if self.text1:
            content += self.text5 + " "
        if self.text1:
            content += self.text6 + " "
        if self.text1:
            content += self.text7 + " "
        if self.text1:
            content += self.text8 + " "
        if self.text1:
            content += self.text9 + " "
        if self.text1:
            content += self.text10
        content = " ".join(findall(r'[\w ]+', content))
        for w in content.lower().split():
            find_pages = Search.objects.filter(word=w)
            if find_pages:
                find_pages[0].pages.add(Page.objects.get(id=self.parent_id))
                find_pages[0].save()
            else:
                s = Search(word=w)
                s.save()
                s.pages.add(Page.objects.get(id=self.parent_id))
                s.save()
Exemple #21
0
class SectionContent(models.Model):
    """
    Title, media file and rich text fields in one content block.
    """

    feincms_item_editor_inline = SectionContentInline
    feincms_item_editor_context_processors = (
        lambda x: settings.FEINCMS_RICHTEXT_INIT_CONTEXT,
    )
    feincms_item_editor_includes = {
        'head': [settings.FEINCMS_RICHTEXT_INIT_TEMPLATE],
    }

    title = models.CharField(_('title'), max_length=200, blank=True)
    richtext = RichTextField(_('text'), blank=True)
    mediafile = MediaFileForeignKey(MediaFile, verbose_name=_('media file'),
        related_name='+', blank=True, null=True)

    class Meta:
        abstract = True
        verbose_name = _('section')
        verbose_name_plural = _('sections')

    @classmethod
    def initialize_type(cls, TYPE_CHOICES=None, cleanse=False):
        if 'feincms.module.medialibrary' not in django_settings.INSTALLED_APPS:
            raise ImproperlyConfigured, 'You have to add \'feincms.module.medialibrary\' to your INSTALLED_APPS before creating a %s' % cls.__name__

        if TYPE_CHOICES is None:
            raise ImproperlyConfigured, 'You need to set TYPE_CHOICES when creating a %s' % cls.__name__

        cls.add_to_class('type', models.CharField(_('type'),
            max_length=10, choices=TYPE_CHOICES,
            default=TYPE_CHOICES[0][0]))

        if cleanse:
            # If cleanse is True use default cleanse method
            if cleanse == True:
                import warnings
                warnings.warn("Please pass a callable instead. cleanse=True is"
                    " being deprecated in favor of explicitly specifying the"
                    " cleansing function. To continue using the same"
                    " functionality, pip install feincms-cleanse and pass"
                    " cleanse=feincms_cleanse.cleanse_html to the"
                    " create_content_type call."
                    " Support for cleanse=True will be removed in FeinCMS v1.8.",
                    DeprecationWarning, stacklevel=2)

                from feincms.utils.html.cleanse import cleanse_html
                cls.cleanse = cleanse_html
            # Otherwise use passed callable
            else:
                cls.cleanse = cleanse

    @classmethod
    def get_queryset(cls, filter_args):
        # Explicitly add nullable FK mediafile to minimize the DB query count
        return cls.objects.select_related('parent', 'mediafile').filter(filter_args)

    def render(self, **kwargs):
        if self.mediafile:
            mediafile_type = self.mediafile.type
        else:
            mediafile_type = 'nomedia'

        return render_to_string([
            'content/section/%s_%s.html' % (self.type, mediafile_type),
            'content/section/%s.html' % self.type,
            'content/section/%s.html' % mediafile_type,
            'content/section/default.html',
            ], {'content': self})

    def save(self, *args, **kwargs):
        if getattr(self, 'cleanse', False):
            try:
                # Passes the rich text content as first argument because
                # the passed callable has been converted into a bound method
                self.richtext = self.cleanse(self.text)
            except TypeError:
                # Call the original callable, does not pass the rich richtext
                # content instance along
                self.richtext = self.cleanse.im_func(self.text)

        super(SectionContent, self).save(*args, **kwargs)
    save.alters_data = True