Пример #1
0
class Ability(index.Indexed, models.Model):
    name = models.TextField(blank=False)
    image = models.ForeignKey('wagtailimages.Image',
                              null=True,
                              blank=False,
                              on_delete=models.SET_NULL,
                              related_name='+')
    summary = RichTextField(features=configurations.RICHTEXT_FEATURES,
                            blank=False,
                            null=False)
    farsi_summary = RichTextField(features=configurations.RICHTEXT_FEATURES,
                                  blank=False,
                                  null=False)

    panels = [
        FieldPanel('name'),
        ImageChooserPanel('image'),
        RichTextFieldPanel('summary'),
        RichTextFieldPanel('farsi_summary'),
    ]

    search_fields = [index.SearchField('name', partial_match=True)]

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name', )
        verbose_name_plural = 'Abilities'
Пример #2
0
class PostPage(Page):
    body = RichTextField()
    date = models.DateTimeField(verbose_name="Post date", default=datetime.datetime.today)
    excerpt = RichTextField(
        verbose_name='excerpt', blank=True,
    )

    header_image = models.ForeignKey(
        'wagtailimages.Image',
        null=True, blank=True,
        on_delete=models.SET_NULL,
        related_name='+',
    )

    categories = ParentalManyToManyField('pgd.BlogCategory', blank=True)
    tags = ClusterTaggableManager(through='pgd.BlogPageTag', blank=True)

    content_panels = Page.content_panels + [
        ImageChooserPanel('header_image'),
        RichTextFieldPanel("body"),
        RichTextFieldPanel("excerpt"),
        FieldPanel('categories', widget=forms.CheckboxSelectMultiple),
        FieldPanel('tags'),
        InlinePanel('post_gallery_images', label="Gallery"),
    ]

    settings_panels = Page.settings_panels + [
        FieldPanel('date'),
    ]

    parent_page_types = ['pgd.BlogPage']
    subpage_types = []

    @property
    def blog_page(self):
        return self.get_parent().specific

    def get_context(self, request, *args, **kwargs):
        context = super(PostPage, self).get_context(request, *args, **kwargs)
        context['blog_page'] = self.blog_page
        context['blog_latest_posts'] = PostPage.objects.descendant_of(self.get_parent().specific).live().order_by('-date')
        context['post'] = self
        return context

    show_in_menus_default = True

    class Meta:
        verbose_name = "article"
        verbose_name_plural = "articles"
Пример #3
0
class EndNote(Orderable):
    text = RichTextField()
    uuid = models.CharField(max_length=64, blank=True)
    article = ParentalKey("articles.ArticlePage",
                          null=True,
                          on_delete=models.SET_NULL,
                          related_name='endnote_links')

    def __init__(self, *args, **kwargs):
        super(EndNote, self).__init__(*args, **kwargs)
        if not self.uuid:
            self.uuid = get_uuid()

    def save(self, *args, **kwargs):
        if not self.uuid:
            self.uuid = get_uuid()
        super(EndNote, self).save()

    def __str__(self):
        return self.text

    panels = [
        RichTextFieldPanel('text'),
        FieldPanel('uuid', widget=HiddenInput),
    ]
Пример #4
0
class FormPage(AbstractEmailForm):
    image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )
    body = RichTextField(verbose_name="Form body", blank=True)
    thank_you_text = RichTextField(blank=True)

    # Note how we include the FormField object via an InlinePanel using the
    # related_name value
    content_panels = AbstractEmailForm.content_panels + [
        ImageChooserPanel('image'),
        RichTextFieldPanel('body'),
        InlinePanel('form_fields', label="Form fields"),
        FieldPanel('thank_you_text', classname="full"),
        MultiFieldPanel([
            FieldRowPanel([
                FieldPanel('from_address', classname="col6"),
                FieldPanel('to_address', classname="col6"),
            ]),
            FieldPanel('subject'),
        ], "Email"),
    ]
Пример #5
0
class BasePage(Page):
    """ Basic page that takes an introduction, an image, and a body. This can be used to write the about us page, etc.
    """

    introduction = models.TextField(help_text='Text to describe the page',
                                    blank=True)
    image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+',
        help_text=
        'Landscape mode only; horizontal width between 1000px and 3000px.')
    body = StreamField(BaseStreamBlock(), verbose_name="Page body", blank=True)
    content_panels = Page.content_panels + [
        RichTextFieldPanel('introduction', classname="full"),
        StreamFieldPanel('body'),
        ImageChooserPanel('image'),
    ]

    def get_context(self, request):
        context = super(BasePage, self).get_context(request)
        # Very silly way of getting the first word of the title and use it as template context
        c = self.title.split(' ')[0].lower()
        context['wrapper_class'] = c
        context['intro_class'] = c
        return context
Пример #6
0
class SubjectKeyStageCard(Orderable):
    '''Between 1 and 4 '''

    page = ParentalKey('subject.SubjectLandingPage', related_name='key_stage_card')
    title = models.CharField(max_length=20, null=False, blank=False, unique=True, help_text="Enter the Key Stage Level")
    description = RichTextField(max_length=200, null=False, blank=False, help_text="Enter information about what this Key Stage covers", features=['h4', 'h5', 'bold', 'italic', ])

    
    content = StreamField(
        [
            ("test", blocks.SubjectModuleBlock()),
            
        ],
        null=True,
        blank=True
    )
    
    
    panels = [
        FieldPanel('title', heading="Key Stage"),
        RichTextFieldPanel('description'),
        StreamFieldPanel('content'),
    ]

    
Пример #7
0
class ContentPage(Page):
    """A simple :class:`Page` type for content pages."""

    # fields
    description = models.TextField(blank=True)
    body = RichTextField(
        features=[
            "h2",
            "h3",
            "bold",
            "italic",
            "link",
            "ol",
            "ul",
            "image",
            "embed",
            "blockquote",
            "superscript",
            "subscript",
            "strikethrough",
        ],
        blank=True,
    )
    # can be child of Home or Container page
    parent_page_types = [HomePage, ContainerPage]
    content_panels = Page.content_panels + [
        FieldPanel("description"),
        RichTextFieldPanel("body"),
    ]

    def get_context(self, request):
        context = super(ContentPage, self).get_context(request)
        context["page_type"] = "content-page"
        return context
Пример #8
0
class Publication(Page):
    # SETTINGS
    template = "project/publication_detail.html"
    parent_page_types = ['projects.PublicationListingPage']
    # FIELDS
    pub_title = models.CharField(max_length=150, null=True, blank=False)
    pub_abstract = RichTextField(blank=False,
                                 null=True,
                                 help_text="Publication abstract")
    pub_journal = models.TextField(null=True,
                                   blank=False,
                                   verbose_name='Journal of Publication')
    pub_link = models.URLField(null=True,
                               blank=True,
                               help_text='Link to publication')
    pub_date = models.DateField(
        blank=True,
        null=True,
        verbose_name='Publication Date',
        help_text='The rough date when this publication was published.')
    gs_project = models.ForeignKey('projects.Project',
                                   null=True,
                                   blank=True,
                                   related_name='publications',
                                   on_delete=models.SET_NULL)

    categories = ParentalManyToManyField('blog.BlogCategory')

    search_fields = Page.search_fields + [
        index.SearchField('pub_title'),
        index.SearchField('pub_abstract'),
        index.SearchField('pub_journal'),
        index.SearchField('categories'),
        index.SearchField('authors')
    ]

    content_panels = Page.content_panels + [
        FieldPanel('pub_title'),
        RichTextFieldPanel('pub_abstract'),
        FieldPanel('pub_journal'),
        FieldPanel('pub_link'),
        MultiFieldPanel(
            [FieldPanel('categories', widget=forms.CheckboxSelectMultiple)]),
        PageChooserPanel('gs_project'),
        MultiFieldPanel([InlinePanel('authors', label="Author", min_num=1)],
                        heading='Publication Authors'),
    ]

    api_fields = [
        APIField('pub_title'),
        APIField('pub_abstract'),
        APIField('gs_project'),
        APIField('pub_link'),
        APIField('authors'),
        APIField('categories'),
    ]

    class Meta:
        verbose_name = 'Publication'
        verbose_name_plural = 'Publications'
Пример #9
0
class ConcordanceEntryMixin(models.Model):
    """
    A mixin for any page that should have common concordance fields.
    """

    subtitle = models.TextField(blank=True)

    lead = RichTextField(blank=True)

    hero_image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )

    body = StreamField(COMMON_BLOCKS)

    content_panels = Page.content_panels + [
        ImageChooserPanel('hero_image'),
        FieldPanel('subtitle'),
        RichTextFieldPanel('lead'),
        StreamFieldPanel('body'),
    ]

    class Meta:
        abstract = True
Пример #10
0
class BlogPost(models.Model):
    post_title = RichTextField(
        features=[],
        blank=False,
        null=True,
    )
    post_summary = RichTextField(
        features=configurations.RICHTEXT_FEATURES,
        blank=False,
        null=True,
    )
    post_introduction = RichTextField(
        features=configurations.RICHTEXT_FEATURES,
        blank=True,
        null=True,
    )
    post_conclusion = RichTextField(
        features=configurations.RICHTEXT_FEATURES,
        blank=True,
        null=True,
    )
    sections = StreamField([
        ('section', SectionBlock()),
    ], blank=False)

    panels = [
        MultiFieldPanel([
            RichTextFieldPanel('post_title'),
            RichTextFieldPanel('post_summary'),
            RichTextFieldPanel('post_introduction'),
            StreamFieldPanel('sections'),
            RichTextFieldPanel('post_conclusion'),
        ],
                        heading='Post Content'),
    ]

    @property
    def sections_with_title(self):
        sections = []
        for section in self.sections:
            if section.value['title']:
                sections.append(section)
        return sections

    def __str__(self):
        return text_processing.html_to_str(self.post_title)
Пример #11
0
class Citation(Orderable):
    text = RichTextField()
    article = ParentalKey("articles.ArticlePage",
                          related_name='citation_links')

    def __str__(self):
        return self.text

    panels = [
        RichTextFieldPanel('text'),
    ]
Пример #12
0
class HomePage(PersonalisablePageMixin, Page):
    intro = RichTextField()
    body = StreamField([('personalisable_paragraph',
                         PersonalisedStructBlock([
                             ('paragraph', blocks.RichTextBlock()),
                         ],
                                                 icon='pilcrow'))])

    content_panels = Page.content_panels + [
        RichTextFieldPanel('intro'),
        StreamFieldPanel('body'),
    ]
Пример #13
0
class ArticlePage(BasePage):
    author = models.TextField(blank=True, null=True, verbose_name=_("Author"))
    wysiwyg = RichTextField(blank=True, null=True, verbose_name=_("Wysiwyg"))

    content_panels = BasePage.content_panels + [
        FieldPanel("author"),
        RichTextFieldPanel("wysiwyg"),
    ]

    extra_panels = BasePage.extra_panels

    class Meta:
        verbose_name = _("Article")
Пример #14
0
class ArticlePage(BasePage):
    rich_text = RichTextField(blank=True,
                              null=True,
                              verbose_name=_("Rich text"))

    content_panels = BasePage.content_panels + [
        RichTextFieldPanel("rich_text")
    ]

    extra_panels = BasePage.extra_panels
    serializer_class = "main.pages.ArticlePageSerializer"

    class Meta:
        verbose_name = _("Article")
Пример #15
0
class PublicationListingPage(RoutablePageMixin, Page):
    """Return a list of published Publication pages."""
    # SETTINGS
    template = 'project/publication_list.html'
    parent_page_types = ['home.HomePage']
    # FIELDS
    page_title = models.CharField(max_length=120,
                                  blank=False,
                                  null=True,
                                  help_text="Title for List of Publications")
    page_subtitle = RichTextField(blank=True,
                                  null=True,
                                  help_text='Sub title text for listing page.')
    pubs_per_page = models.IntegerField(
        default=5,
        verbose_name='Publications per Page',
        help_text='Define how this listing is paginated')

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        all_publications = Publication.objects.live().public().order_by(
            '-pub_date')
        # Adding pagination
        paginator = Paginator(all_publications, self.pubs_per_page)
        page = request.GET.get('page')
        try:
            posts = paginator.page(page)
        except PageNotAnInteger:
            posts = paginator.page(1)
        except EmptyPage:
            posts = paginator.page(paginator.num_pages)

        context['posts'] = posts
        context['categories'] = BlogCategory.objects.all()
        return context

    api_fields = [
        APIField('page_title'),
        APIField('page_subtitle'),
    ]
    content_panels = Page.content_panels + [
        FieldPanel('page_title'),
        RichTextFieldPanel('page_subtitle'),
        FieldPanel('pubs_per_page')
    ]

    class Meta:
        verbose_name = 'Publication Listing'
        verbose_name_plural = 'Publication Listings'
Пример #16
0
class SubjectKSLandingPage(Page):
        '''KS Landing Page Per Subject'''
                
        class Meta:
            verbose_name = "Key Stage Description for Subject"
        
        templates  = 'subject/subject_KS_landing_page.html'
        parent_page_types = ["subject.SubjectLandingPage"]
        
        
        description = models.TextField(
            blank=False, 
            null=True,
            max_length= 200,
            help_text = "Please insert a short description as to what this Key Stage covers"
        )
        
        internal_page = models.ForeignKey(
            'wagtailcore.Page',
             on_delete=models.SET_NULL,
             blank = True,
             null = True,
             related_name = "+",
             help_text = "Set an internal page",
        )
        
        image = models.ForeignKey(
            'wagtailimages.Image',
            null=True,
            blank = False,
            on_delete = models.SET_NULL,
            related_name = "+",
            help_text = "This will be used on the listing page and will be cropped"
        )
          
        content_panels = Page.content_panels + [
        
            FieldPanel('title', heading="Key Stage"),
            RichTextFieldPanel('description'),
            ImageChooserPanel('image'),
            PageChooserPanel('internal_page')
    ]

        def get_context(self,request,*args,**kwargs):
            context = super().get_context(request,*args,**kwargs)
            context["modules"] = self.get_children().live().public()
            return context
Пример #17
0
class JobPostingPage(ThemeablePage, ShareLinksMixin):
    body = RichTextField()

    content_panels = Page.content_panels + [
        RichTextFieldPanel('body'),
    ]

    style_panels = ThemeablePage.style_panels

    edit_handler = TabbedInterface([
        ObjectList(content_panels, heading='Content'),
        ObjectList(style_panels, heading='Page Style Options'),
        ObjectList(Page.promote_panels, heading='Promote'),
        ObjectList(Page.settings_panels,
                   heading='Settings',
                   classname="settings"),
    ])
Пример #18
0
class ProjectList(RoutablePageMixin, Page):

    # SETTINGS
    template = 'project/project_list.html'
    parent_page_types = ['home.HomePage']
    # FIELDS
    page_title = models.CharField(max_length=120,
                                  blank=False,
                                  null=True,
                                  help_text='Title for list of Projects')
    page_subtitle = RichTextField(blank=True,
                                  null=True,
                                  help_text='Sub title text for listing page.')
    projects_per_page = models.IntegerField(
        default=5,
        verbose_name='Projects per Page',
        help_text='Number of projects per page.')

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        all_projects = Project.objects.live().public().order_by(
            '-first_published_at')
        paginator = Paginator(all_projects, self.projects_per_page)
        page = request.GET.get('page')
        try:
            posts = paginator.page(page)
        except PageNotAnInteger:
            posts = paginator.page(1)
        except EmptyPage:
            posts = paginator.page(paginator.num_pages)

        context['posts'] = posts
        context['categories'] = BlogCategory.objects.all()
        return context

    api_fields = [APIField('page_title'), APIField('page_subtitle')]
    content_panels = Page.content_panels + [
        FieldPanel('page_title'),
        RichTextFieldPanel('page_subtitle'),
        FieldPanel('projects_per_page')
    ]

    class Meta:
        verbose_name = 'Project Listing'
        verbose_name_plural = 'Project Listings'
Пример #19
0
class BrandAbstract(models.Model, index.Indexed):
    name = models.TextField(verbose_name=_('name'),
                            unique=True,
                            null=False,
                            blank=False,
                            default=None)
    image = models.ForeignKey(get_image_model_string(),
                              null=True,
                              blank=True,
                              on_delete=models.SET_NULL,
                              related_name='+',
                              verbose_name=_('product image'))
    description = RichTextField()
    count_related_products = models.IntegerField(
        verbose_name=_('number of related products'),
        null=False,
        blank=False,
        default=0)

    panels = [
        MultiFieldPanel([
            FieldPanel('name', classname='title'),
            ImageChooserPanel('image'),
            RichTextFieldPanel('description', classname='full-width')
        ],
                        heading=_('General Product Information'))
    ]

    api_fields = [
        APIField('name'),
        APIField('image'),
        APIField('description'),
        APIField('count_related_products')
    ]

    search_fields = [index.SearchField('name', boost=10, partial_match=True)]

    def __str__(self) -> str:
        return self.name

    class Meta:
        abstract = True
Пример #20
0
class Project(models.Model):
    title = models.CharField(max_length=255)
    description = RichTextField(
        features=["h2", "h3", "bold", "italic", "link"])
    geographic_area = models.PolygonField(geography=True,
                                          null=True,
                                          blank=True)

    panels = [
        FieldPanel("title"),
        RichTextFieldPanel("description"),
        FieldPanel("geographic_area", widget=OSMWidget),
    ]

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("project_view", kwargs={
            "pk": self.pk,
        })
Пример #21
0
class HomePage(Page, TextAnalysis):
    wysiwyg = RichTextField(blank=True, null=True, verbose_name=_("Wysiwyg"))
    tags = ClusterTaggableManager(through=HomePageTag, blank=True)

    content_panels = Page.content_panels + [
        RichTextFieldPanel("wysiwyg"),
        FieldPanel('tags'),
    ]

    text_analysis_fields = [
        KeyPhrasesField('title'),
        KeyPhrasesField('wysiwyg'),
    ]

    def update_key_phrases(self, phrases):
        page_revision = self.get_latest_revision_as_page()
        page_revision.tags.add(*phrases)

        revision = self.get_latest_revision()
        revision.content_json = page_revision.to_json()
        revision.save()
Пример #22
0
class ContentSection(Page, SectionBase):
    """A content section with an WYSIWYG Richtext editro"""
    content_richtext = RichTextField()

    # basic tab panels
    basic_panels = Page.content_panels + [
        SectionBase.section_content_panels,
        RichTextFieldPanel(
            'content_richtext',
            heading='Richtext',
        ),
        SectionBase.section_layout_panels,
        SectionBase.section_design_panels,
    ]

    # Register Tabs
    edit_handler = TabbedInterface([
        ObjectList(basic_panels, heading="Basic"),
    ])

    # Page settings
    template = 'sections/content_section_preview.html'
    parent_page_types = ['home.HomePage']
    subpage_types = []

    # Overring methods
    def set_url_path(self, parent):
        """
        Populate the url_path field based on this page's slug and the specified parent page.
        (We pass a parent in here, rather than retrieving it via get_parent, so that we can give
        new unsaved pages a meaningful URL when previewing them; at that point the page has not
        been assigned a position in the tree, as far as treebeard is concerned.
        """
        if parent:
            self.url_path = ''
        else:
            # a page without a parent is the tree root, which always has a url_path of '/'
            self.url_path = '/'

        return self.url_path
Пример #23
0
class ProjectPage(ThemeablePage):
    description = RichTextField(blank=True, default="")

    search_fields = Page.search_fields + [
        index.SearchField('description', partial_match=True),
    ]

    def search_result_text(self):
        if self.description:
            self.search_result_text = self.description[0:240]
        return self.search_result_text

    def project_articles(self):
        return self.articlepage_set.filter(live=True).order_by("-first_published_at")

    def project_series(self):
        return self.seriespage_set.filter(live=True).order_by("-first_published_at")

    def get_related_series(self, series_page):
        return self.seriespage_set.filter(live=True).exclude(pk=series_page.pk).order_by("-first_published_at")

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

    content_panels = Page.content_panels + [
        RichTextFieldPanel('description'),
    ]

    style_panels = ThemeablePage.style_panels

    edit_handler = TabbedInterface([
        ObjectList(content_panels, heading='Content'),
        ObjectList(style_panels, heading='Page Style Options'),
        ObjectList(Page.promote_panels, heading='Promote'),
        ObjectList(Page.settings_panels, heading='Settings', classname="settings"),
    ])
Пример #24
0
class HomePage(Page):
    """:class:`wagtail.core.models.Page` model for Geniza home page."""

    # fields
    description = models.TextField(blank=True)
    body = RichTextField(
        features=[
            "h2",
            "h3",
            "bold",
            "italic",
            "link",
            "ol",
            "ul",
            "image",
            "embed",
            "blockquote",
            "superscript",
            "subscript",
            "strikethrough",
        ],
        blank=True,
    )
    # can only be child of Root
    parent_page_types = [Page]
    subpage_types = ["pages.ContentPage", "pages.ContainerPage"]
    content_panels = Page.content_panels + [
        FieldPanel("description"),
        RichTextFieldPanel("body"),
    ]

    class Meta:
        verbose_name = "homepage"

    def get_context(self, request):
        context = super(HomePage, self).get_context(request)
        context["page_type"] = "homepage"
        return context
Пример #25
0
class StandardPage(Page):
    """
    A generic content page. On the site we use it for an about page but
    it could be used for any type of page content that only needs a title,
    image, introduction and body field
    """
    introduction = models.TextField(
        help_text='Text to describe the page',
        blank=True)

    image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+',
        help_text='Landscape mode only; horizontal width between 1000px and 3000px.'
    )
    body = RichTextField(verbose_name="Page body", blank=True)
    content_panels = Page.content_panels + [
        FieldPanel('introduction', classname="full"),
        RichTextFieldPanel('body'),
        ImageChooserPanel('image'),
    ]
Пример #26
0
class ActionAdmin(AplansModelAdmin):
    model = Action
    menu_icon = 'wagtail'  # change as required
    menu_order = 201  # will put in 3rd place (000 being 1st, 100 2nd)
    exclude_from_explorer = False  # or True to exclude pages of this type from Wagtail's explorer view
    list_display = ('identifier', 'name')
    # list_filter = ('author',)
    search_fields = ('identifier', 'name')
    list_display_add_buttons = 'name'

    basic_panels = [
        FieldPanel('identifier'),
        FieldPanel('official_name'),
        FieldPanel('name', classname='full title'),
        RichTextFieldPanel('description'),
    ]

    internal_panel = AdminOnlyPanel([
        FieldPanel('internal_priority'),
        FieldPanel('internal_priority_comment'),
        FieldPanel('impact'),
    ], heading=_('Internal information'))

    edit_handler = ActionEditHandler([
        ObjectList(basic_panels, heading=_('Basic information')),
        internal_panel,
        # ObjectList([InlinePanel('responsible_parties')], heading=_('Responsibles')),
        ObjectList([InlinePanel('tasks')], heading=_('Tasks')),
    ])

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        plan = request.user.get_active_admin_plan()
        if not request.user.is_general_admin_for_plan(plan):
            qs = qs.unmerged()
        return qs.filter(plan=plan)
Пример #27
0
class ShortPostPage(AllDotaPageMixin, LogoContainingPageMixin,
                    MetadataPageMixin, MultilingualPageMixin, Page):
    image = models.ForeignKey('wagtailimages.Image',
                              null=True,
                              blank=False,
                              on_delete=models.SET_NULL,
                              related_name='+')

    english_caption = RichTextField(
        features=[],
        blank=False,
        null=True,
    )

    farsi_caption = RichTextField(
        features=[],
        blank=False,
        null=True,
        help_text='It has to start with a farsi word')

    english_tags = ClusterTaggableManager(
        through=ShortPostPageEnglishTag,
        blank=True,
        related_name='short_post_english_tags')
    farsi_tags = ClusterTaggableManager(through=ShortPostPageFarsiTag,
                                        blank=True,
                                        related_name='short_post_farsi_tags')

    content_panels = [
        MultiFieldPanel([ImageChooserPanel('image')],
                        heading='image',
                        classname='collapsible collapsed'),
        MultiFieldPanel([
            RichTextFieldPanel('farsi_caption'),
            FieldPanel('farsi_tags'),
        ],
                        heading='farsi',
                        classname='collapsible collapsed'),
        MultiFieldPanel([
            RichTextFieldPanel('english_caption'),
            FieldPanel('english_tags'),
        ],
                        heading='english',
                        classname='collapsible collapsed'),
    ]
    promote_panels = []
    settings_panels = []

    @property
    def farsi_url(self):
        return super().get_farsi_url()

    @property
    def english_url(self):
        return super().get_english_url()

    @property
    def template(self):
        return super().template

    @property
    def farsi_translated(self):
        return True

    @property
    def english_translated(self):
        return True

    def serve(self, request, *args, **kwargs):
        language = translation.get_language()
        if language == 'en':
            self.search_description = text_processing.html_to_str(
                self.english_caption)
            self.seo_title = self.title
        else:
            self.search_description = text_processing.html_to_str(
                self.farsi_caption)
            self.seo_title = self.title
        return super().serve(request, *args, **kwargs)

    def clean(self):
        super().clean()
        if self.image and self.image.title:
            self.title = self.image.title
            pages = ShortPostPage.objects.filter(title=self.title)
            if pages:
                if not self.id:
                    self.set_uuid4()
                    self.slug = slugify('{}_{}'.format(self.title, self.uuid4))
                else:
                    self.slug = slugify('{}_{}'.format(self.title, self.id))

    uuid4 = models.TextField(default='', blank=True)

    def set_uuid4(self):
        uuid4 = uuid.uuid4()
        while ShortVideoPage.objects.filter(uuid4=uuid4).exists():
            uuid4 = uuid.uuid4()
        self.uuid4 = str(uuid4)

    parent_page_types = [
        'home.ShortPostsPage',
    ]
    subpage_types = []

    def __str__(self):
        return self.english_title
Пример #28
0
class ShortVideoPage(AllDotaPageMixin, LogoContainingPageMixin,
                     MetadataPageMixin, MultilingualPageMixin, Page):
    video = models.ForeignKey('wagtailmedia.Media',
                              null=True,
                              blank=False,
                              on_delete=models.SET_NULL,
                              related_name='+')

    video_thumbnail = models.ForeignKey('wagtailimages.Image',
                                        null=True,
                                        blank=True,
                                        on_delete=models.SET_NULL,
                                        related_name='+')

    @property
    def thumbnail(self):
        if self.video_thumbnail:
            return self.video_thumbnail
        else:
            return self.update_thumbnail()

    def update_thumbnail(self):
        generated_file = False
        if self.video.thumbnail:
            file = open(self.video.thumbnail.path, 'rb')
            file = File(file)
        else:
            clip = cv2.VideoCapture(self.video.file.path)
            ret, frame = clip.read()
            generated_file = 'thumbnail.jpeg'
            cv2.imwrite(generated_file, frame)
            file = open(generated_file, 'rb')
            file = File(file)
        thumbnail = Image(title=text_processing.html_to_str(
            self.english_title),
                          file=file)
        thumbnail.save()
        self.video_thumbnail = thumbnail
        self.save()
        if generated_file:
            os.remove(generated_file)
        return thumbnail

    english_title = RichTextField(features=[], blank=False, null=True)

    farsi_title = RichTextField(features=[],
                                blank=False,
                                null=True,
                                help_text='It has to start with a farsi word')

    english_caption = RichTextField(
        features=[],
        blank=False,
        null=True,
    )

    farsi_caption = RichTextField(
        features=[],
        blank=False,
        null=True,
        help_text='It has to start with a farsi word')

    english_tags = ClusterTaggableManager(through=ShortVideoPageEnglishTag,
                                          blank=True,
                                          related_name='english_tags')
    farsi_tags = ClusterTaggableManager(through=ShortVideoPageFarsiTag,
                                        blank=True,
                                        related_name='farsi_tags')

    content_panels = [
        MultiFieldPanel([
            MediaChooserPanel('video'),
        ],
                        heading='video',
                        classname='collapsible collapsed'),
        MultiFieldPanel([
            FieldPanel('farsi_title'),
            RichTextFieldPanel('farsi_caption'),
            FieldPanel('farsi_tags'),
        ],
                        heading='farsi',
                        classname='collapsible collapsed'),
        MultiFieldPanel([
            FieldPanel('english_title'),
            RichTextFieldPanel('english_caption'),
            FieldPanel('english_tags'),
        ],
                        heading='english',
                        classname='collapsible collapsed'),
    ]
    promote_panels = []
    settings_panels = []

    @property
    def farsi_url(self):
        return super().get_farsi_url()

    @property
    def english_url(self):
        return super().get_english_url()

    @property
    def template(self):
        return super().template

    @property
    def farsi_translated(self):
        return True

    @property
    def english_translated(self):
        return True

    def serve(self, request, *args, **kwargs):
        language = translation.get_language()
        if language == 'fa':
            self.search_description = text_processing.html_to_str(
                self.english_caption)
            self.seo_title = text_processing.html_to_str(self.english_title)
        else:
            self.search_description = text_processing.html_to_str(
                self.farsi_caption)
            self.seo_title = text_processing.html_to_str(self.farsi_title)
        return super().serve(request, *args, **kwargs)

    def clean(self):
        super().clean()
        if self.english_title:
            self.title = text_processing.html_to_str(self.english_title)
            pages = ShortVideoPage.objects.filter(title=self.title)
            if pages:
                if not self.id:
                    self.set_uuid4()
                    self.slug = slugify('{}_{}'.format(self.title, self.uuid4))
                else:
                    self.slug = slugify('{}_{}'.format(self.title, self.id))

    uuid4 = models.TextField(default='', blank=True)

    def set_uuid4(self):
        uuid4 = uuid.uuid4()
        while ShortVideoPage.objects.filter(uuid4=uuid4).exists():
            uuid4 = uuid.uuid4()
        self.uuid4 = str(uuid4)

    parent_page_types = ['home.ShortVideosPage']
    subpage_types = []

    def __str__(self):
        return self.english_title
Пример #29
0
class ActionTask(models.Model):
    NOT_STARTED = 'not_started'
    IN_PROGRESS = 'in_progress'
    CANCELLED = 'cancelled'
    COMPLETED = 'completed'

    STATES = (
        (NOT_STARTED, _('not started')),
        (IN_PROGRESS, _('in progress')),
        (COMPLETED, _('completed')),
        (CANCELLED, _('cancelled')),
    )

    action = ParentalKey(Action,
                         on_delete=models.CASCADE,
                         related_name='tasks',
                         verbose_name=_('action'))
    name = models.CharField(max_length=250, verbose_name=_('name'))
    state = models.CharField(max_length=20,
                             choices=STATES,
                             default=NOT_STARTED,
                             verbose_name=_('state'))
    comment = RichTextField(null=True, blank=True, verbose_name=_('comment'))
    due_at = models.DateField(
        verbose_name=_('due date'),
        help_text=_(
            'The date by which the task should be completed (deadline)'))
    completed_at = models.DateField(
        null=True,
        blank=True,
        verbose_name=_('completion date'),
        help_text=_('The date when the task was completed'))

    completed_by = models.ForeignKey(User,
                                     null=True,
                                     blank=True,
                                     on_delete=models.SET_NULL,
                                     verbose_name=_('completed by'),
                                     editable=False)
    created_at = models.DateTimeField(auto_now_add=True,
                                      editable=False,
                                      verbose_name=_('created at'))
    modified_at = models.DateTimeField(auto_now=True,
                                       editable=False,
                                       verbose_name=_('modified at'))

    sent_notifications = GenericRelation('notifications.SentNotification',
                                         related_query_name='action_task')

    objects = ActionTaskQuerySet.as_manager()

    panels = [
        FieldPanel('name'),
        FieldPanel('due_at'),
        FieldPanel('completed_at'),
        RichTextFieldPanel('comment'),
    ]

    class Meta:
        ordering = ('action', 'due_at')
        verbose_name = _('action task')
        verbose_name_plural = _('action tasks')

    def __str__(self):
        return self.name

    def clean(self):
        if self.state == ActionTask.COMPLETED and self.completed_at is None:
            raise ValidationError({
                'completed_at':
                _('Completed tasks must have a completion date')
            })
        if self.completed_at is not None and self.completed_at > date.today():
            raise ValidationError(
                {'completed_at': _("Date can't be in the future")})

    def get_notification_context(self):
        return {
            'action': self.action.get_notification_context(),
            'name': self.name,
            'due_at': self.due_at,
            'state': self.state
        }
Пример #30
0
class HomePage(Page):

    # Header
    header_lead = models.CharField(
        verbose_name=_('Slogan'),
        max_length=255,
        blank=True,
        default='',
    )
    header_heading = models.CharField(
        verbose_name=_('Titre'),
        max_length=128,
        default='',
    )
    header_slide = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        verbose_name=_('Slide'),
        related_name='+',
    )

    # About
    biography_heading = models.CharField(
        verbose_name=_('Titre'),
        max_length=128,
        default='',
    )
    biography_subheading = models.CharField(
        verbose_name=_('Sous-titre'),
        max_length=128,
        blank=True,
        default='',
    )
    biography_text = RichTextField(blank=True)

    # Services
    service_subheading = models.CharField(
        verbose_name=_('Sous-titre'),
        max_length=255,
        blank=True,
        default='',
    )
    services = StreamField(
        [('service', ServiceBlock())],
        null=True,
        blank=True,
    )

    # Skills
    skill_heading = models.CharField(
        verbose_name=_('Titre'),
        max_length=255,
        blank=True,
        default='',
    )
    skill_subheading = models.CharField(
        verbose_name=_('Sous-titre'),
        max_length=255,
        blank=True,
        default='',
    )
    skills = StreamField(
        [('skill', SkillBlock())],
        null=True,
        blank=True,
    )

    # Experiences
    experience_heading = models.CharField(
        verbose_name=_('Titre'),
        max_length=255,
        blank=True,
        default='',
    )
    experience_subheading = models.CharField(
        verbose_name=_('Sous-titre'),
        max_length=255,
        blank=True,
        default='',
    )
    experiences = StreamField(
        [('experience', ExperienceBlock())],
        null=True,
        blank=True,
    )

    # Contact
    contact_address = models.CharField(max_length=255, blank=True, default='')
    contact_email = models.EmailField(blank=True, default='')
    contact_phone = models.CharField(max_length=128, blank=True, default='')

    content_panels = Page.content_panels + [
        MultiFieldPanel(
            [
                FieldPanel('header_lead'),
                FieldPanel('header_heading'),
                ImageChooserPanel('header_slide'),
            ],
            heading=_('Entête'),
        ),
        MultiFieldPanel(
            [
                FieldPanel('biography_heading'),
                FieldPanel('biography_subheading'),
                RichTextFieldPanel('biography_text'),
            ],
            heading=_('Biographie'),
        ),
        MultiFieldPanel(
            [
                FieldPanel('service_subheading'),
                StreamFieldPanel('services'),
            ],
            heading=_('Services'),
        ),
        MultiFieldPanel(
            [
                FieldPanel('skill_heading'),
                FieldPanel('skill_subheading'),
                StreamFieldPanel('skills'),
            ],
            heading=_('Compétences'),
        ),
        MultiFieldPanel(
            [
                FieldPanel('experience_heading'),
                FieldPanel('experience_subheading'),
                StreamFieldPanel('experiences'),
            ],
            heading=_('Mon parcours'),
        ),
        MultiFieldPanel(
            [
                FieldPanel('contact_address'),
                FieldPanel('contact_email'),
                FieldPanel('contact_phone'),
            ],
            heading=_('Contact'),
        ),
    ]

    class Meta:
        db_table = 'portfolio_homepage'
        verbose_name = _("Page d'accueil")