Esempio n. 1
0
class Media(models.Model):

    MEDIA_TYPES = Choices(
        (3, _('Books')),
        (4, _('Maps')),
        (8, _('Other documents')),
        (6, _('Photos')),
        (10, _('PR materials')),
        (9, _('Presentations')),
        (1, _('SLM questionnaires')),
        (2, _('Training materials')),
        (5, _('Videos')),
    )

    title = models.CharField(
        'Title',
        max_length=255,
        unique=True
    )
    abstract = models.TextField(
        'Abstract',
        blank=True
    )
    teaser_image = models.ForeignKey(
        'wagtailimages.Image',
        verbose_name='Teaser image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )

    @property
    def image(self):
        return self.teaser_image or None

    video = models.URLField(
        verbose_name='Video',
        blank=True,
    )

    year = models.PositiveIntegerField(
        'Year',
        default=get_default_year_now,
        validators=[MaxValueValidator(4000)],
        blank=True, null=True
    )

    languages = models.ManyToManyField(
        verbose_name='Languages',
        to=Language,
        blank=True
    )

    content = StreamField(
        CORE_BLOCKS,
        blank=True,
    )
    file = models.ForeignKey(
        'wagtaildocs.Document',
        null=True, blank=True,
        on_delete=models.PROTECT,
        related_name='+',
        help_text='This field is only used if the content is empty.',
    )
    author = models.CharField(
        'Author',
        max_length=255,
        blank=True,
    )
    countries = models.ManyToManyField(
        verbose_name='Countries',
        to=Country,
        blank=True,
    )
    continent = models.ForeignKey(
        to=Continent,
        blank=True, null=True,
    )
    media_type = models.IntegerField(
        choices=MEDIA_TYPES, db_column='media_type_id')

    class Meta:
        verbose_name = 'Media'
        verbose_name_plural = 'Media'

    def __str__(self):
        return self.title

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

    panels = [
        FieldPanel('title'),
        FieldPanel('abstract'),
        FieldPanel('media_type'),
        FieldPanel('video'),
        DocumentChooserPanel('file'),
        ImageChooserPanel('teaser_image'),
        FieldPanel('author'),
        FieldPanel('countries'),
        FieldPanel('continent'),
        FieldPanel('year'),
        FieldPanel('languages'),
        StreamFieldPanel('content'),
    ]
Esempio n. 2
0
class SubmitFormPage(
        WagtailCaptchaEmailForm if has_recaptcha() else AbstractEmailForm):
    """
    Form page, inherits from WagtailCaptchaEmailForm if available, otherwise fallback to AbstractEmailForm
    """
    search_fields = []
    body = RichTextField(
        blank=True,
        help_text='Edit the content you want to see before the form.')
    thank_you_text = RichTextField(
        blank=True,
        help_text='Set the message users will see after submitting the form.')

    class Meta:
        verbose_name = "Add a site page"
        description = "Page with the form to submit a new Wagtail site"


SubmitFormPage.content_panels = [
    FieldPanel('title', classname="full title"),
    FieldPanel('body', classname="full"),
    FieldPanel('thank_you_text', classname="full"),
    InlinePanel('form_fields', label="Form fields"),
    MultiFieldPanel([
        FieldPanel('to_address'),
        FieldPanel('from_address'),
        FieldPanel('subject'),
    ], "Email notification")
]
Esempio n. 3
0
class Job(ClusterableModel, index.Indexed):
    title = CharField(max_length=255, unique=True)
    background = RichTextField(blank=True)
    responsibilities = RichTextField(blank=True)
    skills = RichTextField(blank=True)
    notes = RichTextField(blank=True)
    location = RichTextField(blank=True)
    benefits = RichTextField(blank=True)
    applying = StreamField([
        ('raw_html', RawHTMLBlock(
            help_text='To add Google Analytics to your link, use this template: '
                      '<a href="www.example.com" onclick="trackOutboundLink("www.example.com"); return false;">link</a>.'
                      '  With great power comes great responsibility. '
                      'This HTML is unescaped. Be careful!')),
        ('rich_text', RichTextBlock()),
    ], null=True, blank=True)
    core_technologies = RichTextField(blank=True)
    referrals = RichTextField(blank=True)
    preferred = RichTextField(blank=True)
    qualifications = RichTextField(blank=True)
    experience_we_need = RichTextField(blank=True)

    panels = [
        MultiFieldPanel([
            FieldPanel('title'),
            FieldPanel('background'),
            FieldPanel('responsibilities'),
            FieldPanel('skills'),
            FieldPanel('notes'),
            FieldPanel('location'),
            FieldPanel('core_technologies'),
            FieldPanel('qualifications'),
            FieldPanel('experience_we_need'),
            FieldPanel('preferred'),
            FieldPanel('referrals'),
            FieldPanel('benefits'),
            StreamFieldPanel('applying'),
        ]),
    ]

    class Meta:
        ordering = ['title']

    def __str__(self):
        return '{self.title}'.format(self=self)
Esempio n. 4
0
class HomePage(Page):
    body = RichTextField(blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('body', classname="full"),
    ]
Esempio n. 5
0
class BreadsIndexPage(Page):
    """
    Index page for breads.

    This is more complex than other index pages on the bakery demo site as we've
    included pagination. We've separated the different aspects of the index page
    to be discrete functions to make it easier to follow
    """

    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.'
    )

    content_panels = Page.content_panels + [
        FieldPanel('introduction', classname="full"),
        ImageChooserPanel('image'),
    ]

    # Can only have BreadPage children
    subpage_types = ['BreadPage']

    # Returns a queryset of BreadPage objects that are live, that are direct
    # descendants of this index page with most recent first
    def get_breads(self):
        return BreadPage.objects.live().descendant_of(
            self).order_by('-first_published_at')

    # Allows child objects (e.g. BreadPage objects) to be accessible via the
    # template. We use this on the HomePage to display child items of featured
    # content
    def children(self):
        return self.get_children().specific().live()

    # Pagination for the index page. We use the `django.core.paginator` as any
    # standard Django app would, but the difference here being we have it as a
    # method on the model rather than within a view function
    def paginate(self, request, *args):
        page = request.GET.get('page')
        paginator = Paginator(self.get_breads(), 12)
        try:
            pages = paginator.page(page)
        except PageNotAnInteger:
            pages = paginator.page(1)
        except EmptyPage:
            pages = paginator.page(paginator.num_pages)
        return pages

    # Returns the above to the get_context method that is used to populate the
    # template
    def get_context(self, request):
        context = super(BreadsIndexPage, self).get_context(request)

        # BreadPage objects (get_breads) are passed through pagination
        breads = self.paginate(request, self.get_breads())

        context['breads'] = breads

        return context
Esempio n. 6
0
class VisitCountRule(AbstractBaseRule):
    """Visit count rule to segment users based on amount of visits to a
    specified page.

    Matches when the operator and count validate True
    when visiting the set page.

    """
    icon = 'fa-calculator'

    OPERATOR_CHOICES = (
        ('more_than', _("More than")),
        ('less_than', _("Less than")),
        ('equal_to', _("Equal to")),
    )
    operator = models.CharField(max_length=20,
                                choices=OPERATOR_CHOICES, default="more_than")
    count = models.PositiveSmallIntegerField(default=0, null=True)
    counted_page = models.ForeignKey(
        'wagtailcore.Page',
        null=False,
        blank=False,
        on_delete=models.CASCADE,
        related_name='+',
    )

    panels = [
        PageChooserPanel('counted_page'),
        FieldRowPanel([
            FieldPanel('operator'),
            FieldPanel('count'),
        ]),
    ]

    class Meta:
        verbose_name = _('Visit count Rule')

    def test_user(self, request):
        operator = self.operator
        segment_count = self.count

        # Local import for cyclic import
        from wagtail_personalisation.adapters import get_segment_adapter

        adapter = get_segment_adapter(request)

        visit_count = adapter.get_visit_count()
        if visit_count and operator == "more_than":
            if visit_count > segment_count:
                return True
        elif visit_count and operator == "less_than":
            if visit_count < segment_count:
                return True
        elif visit_count and operator == "equal_to":
            if visit_count == segment_count:
                return True
        return False

    def description(self):
        return {
            'title': _('These users visited {}').format(
                self.counted_page
            ),
            'value': _('{} {} times').format(
                self.get_operator_display(),
                self.count
            ),
        }
Esempio n. 7
0
        FieldPanel('intro'),
        FieldPanel('body', classname="full")
    ]


class HomePage(Page):
    body = RichTextField(blank=True)
    intro = models.CharField(max_length=250)
    date = models.DateField("Post date")

    maps = models.ForeignKey('maps.Map',
                             null=True,
                             blank=True,
                             on_delete=models.SET_NULL,
                             related_name='+')

    search_fields = Page.search_fields + [
        index.SearchField('intro'),
        index.SearchField('body'),
    ]

    class Meta:
        verbose_name = "Homepage"


HomePage.content_panels = Page.content_panels + [
    FieldPanel('date'),
    FieldPanel('intro'),
    FieldPanel('body', classname="full"),
    SnippetChooserPanel('maps')
]
    def setUp(self):
        self.EventPageForm = get_form_for_model(EventPage, formsets=[])
        self.event = EventPage(title='Abergavenny sheepdog trials',
                               date_from=date(2014, 7, 20), date_to=date(2014, 7, 21))

        self.EndDatePanel = FieldPanel('date_to', classname='full-width').bind_to_model(EventPage)
Esempio n. 9
0
class Home(AbstractForm):
    def route(self, request, path_components):
        if path_components:
            return RouteResult(self,
                               kwargs={'path_components': path_components})
        else:
            if self.live:
                return RouteResult(self)
            else:
                raise Http404

    banner = RichTextField(blank=True,
                           help_text="Banner at the top of every page")
    header = TextField(blank=True, help_text="Hero title")
    body = RichTextField(blank=True, help_text="Description of page")
    sub_body = RichTextField(
        blank=True, help_text="Text for below the description of the page")
    pyr_text = RichTextField(blank=True, help_text="PYR explanation")
    filter_label_1 = TextField(
        blank=True, help_text="Label/Question for first set of filters")
    filter_label_2 = TextField(
        blank=True, help_text="Label/Question for second set of filters")
    filter_label_3 = TextField(
        blank=True, help_text="Label/Question for third set of filters")
    assessment_text = RichTextField(
        blank=True, help_text="Label for sleep assessment link")
    crisis_text = RichTextField(blank=True,
                                help_text="Label for sleep crisis page link")
    lookingfor = RichTextField(blank=True,
                               help_text="""
        Information on how to leave suggestions and what they are for
        """)
    alpha = RichTextField(blank=True, help_text="What is Alpha")
    alphatext = RichTextField(blank=True,
                              help_text="Why to take part in the alpha")
    footer = RichTextField(blank=True, help_text="Footer text")
    hero_image = models.ForeignKey('wagtailimages.Image',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   related_name='+',
                                   help_text="""
            Max file size: 10MB. Choose from: GIF, JPEG, PNG
            (but pick PNG if you have the choice)
        """)
    video_url = URLField(blank=True,
                         help_text="URL of an introductiary youtube video")
    collections_title = TextField(blank=True, help_text="Title of collections")
    collections_tagline = TextField(blank=True,
                                    help_text="Tagline of collections")
    exclude_tags = ClusterTaggableManager(through=ExcludeTag,
                                          blank=True,
                                          verbose_name="Exclude Tags",
                                          help_text="""
        Tags you do not want to show in the filters for this home page
        """)
    description = RichTextField(blank=True,
                                max_length=206,
                                help_text="""
        A short description of the page that will show on the homepage
    """)
    link_text = TextField(
        blank=True, help_text="Text to display for the link to this page")
    link_color = RGBColorField(
        default='#f3a140',
        null=True,
        blank=True,
        help_text="The link's background colour to use on homepage")
    mobile_title = TextField(blank=True, help_text="Title to show on mobile")
    result_heading = RichTextField(blank=True,
                                   help_text="""
        Heading of result block
    """)
    body_content = RichTextField(blank=True,
                                 help_text="""
        Body of result block
    """)
    footer_content = RichTextField(blank=True,
                                   help_text="""
        Footer of result block
    """)
    image = models.ForeignKey('wagtailimages.Image',
                              null=True,
                              blank=True,
                              on_delete=models.SET_NULL,
                              related_name='+',
                              help_text="""
            Max file size: 10MB. Choose from: JPEG, PNG
        """)
    block_background_color = RGBColorField(
        default='#242e51',
        null=True,
        blank=True,
        help_text="The result block's background colour")
    button_link = models.ForeignKey('wagtailcore.Page',
                                    null=True,
                                    blank=True,
                                    on_delete=models.SET_NULL,
                                    related_name='+')
    pdf_heading = RichTextField(blank=True,
                                help_text="""
        Heading of PDF block
    """)
    pdf_body = RichTextField(blank=True,
                             help_text="""
        Body of PDF block
    """)
    pdf_file = models.ForeignKey('wagtaildocs.Document',
                                 null=True,
                                 blank=True,
                                 on_delete=models.SET_NULL,
                                 related_name='+')
    bottom_link_text = RichTextField(blank=True,
                                     help_text="""
        Link Text of PDF block
    """)
    bottom_link = models.ForeignKey('wagtailcore.Page',
                                    null=True,
                                    blank=True,
                                    on_delete=models.SET_NULL,
                                    related_name='+')

    def get_context(self, request, **kwargs):
        context = super(Home, self).get_context(request)

        context = get_data(request,
                           data=context,
                           slug=self.slug,
                           path_components=kwargs.get('path_components', []))
        return context

    content_panels = AbstractForm.content_panels + [
        InlinePanel('sub_menu', label="SUB MENU"),
        MultiFieldPanel([
            FieldPanel('description'),
            FieldPanel('link_text'),
            FieldPanel('link_color'),
            FieldPanel('mobile_title')
        ],
                        heading="Link Block"),
        ImageChooserPanel('hero_image'),
        FieldPanel('header', classname="full"),
        FieldPanel('body', classname="full"),
        FieldPanel('sub_body', classname="full"),
        FieldPanel('pyr_text', classname="full"),
        FieldPanel('video_url', classname="full"),
        FieldPanel('collections_title', classname="full"),
        FieldPanel('collections_tagline', classname="full"),
        MultiFieldPanel([
            FieldPanel('filter_label_1', classname="full"),
            FieldPanel('filter_label_2', classname="full"),
            FieldPanel('filter_label_3', classname="full"),
            FieldPanel('exclude_tags', classname="full")
        ]),
        MultiFieldPanel([
            FieldPanel('block_background_color'),
            FieldPanel('result_heading', classname="full"),
            FieldPanel('body_content', classname="full"),
            FieldPanel('footer_content', classname="full"),
            ImageChooserPanel('image'),
            PageChooserPanel('button_link'),
        ],
                        heading="Result Block"),
        MultiFieldPanel([
            FieldPanel('pdf_heading'),
            FieldPanel('pdf_body', classname="full"),
            DocumentChooserPanel('pdf_file'),
            FieldPanel('bottom_link_text'),
            PageChooserPanel('bottom_link'),
        ],
                        heading="PDF Block"),
    ]

    def process_form_submission(self, request_dict):
        return custom_form_submission(self, request_dict)

    def serve(self, request, *args, **kwargs):
        request.session['results_page'] = self.slug

        self.__class__.objects.prefetch_related('tagged_items__tag')

        path_components = kwargs.get('path_components', [])

        if kwargs.get('path_components'):
            self.seo_title += f' - {path_components[0]}'

        return custom_serve(**locals())

    def get_sitemap_urls(self):
        sitemap = [{
            'location': self.full_url,
            'lastmod': self.latest_revision_created_at
        }]
        resources = filter_resources(ResourcePage.objects.all(),
                                     topic_filter=self.slug)
        (
            filtered_issue_tags,
            _filtered_reason_tags,
            _filtered_content_tags,
        ) = filter_tags(resources, self.slug)

        issue_tags = get_tags(IssueTag,
                              filtered_tags=filtered_issue_tags).values()

        for t in issue_tags:
            sitemap.append({
                'location': self.full_url + f'{t.name.replace(" ", "-")}/',
                'lastmod': self.latest_revision_created_at
            })

        return sitemap
Esempio n. 10
0
from __future__ import absolute_import, unicode_literals

from wagtail.wagtailadmin.edit_handlers import (FieldPanel, FieldRowPanel,
                                                MultiFieldPanel,
                                                PageChooserPanel, ObjectList,
                                                TabbedInterface)
from django.utils.translation import ugettext_lazy as _

menupage_panel = MultiFieldPanel(heading=_("Advanced menu behaviour"),
                                 classname="collapsible collapsed",
                                 children=(
                                     FieldPanel('repeat_in_subnav'),
                                     FieldPanel('repeated_item_text'),
                                 ))
"""
`settings_panels` arrangement, including new menu-related fields from the
MenuPage abstract class.
"""

menupage_settings_panels = [
    MultiFieldPanel(heading=_("Scheduled publishing"),
                    classname="publishing",
                    children=(FieldRowPanel((
                        FieldPanel('go_live_at', classname="col6"),
                        FieldPanel('expire_at', classname="col6"),
                    )), )),
    menupage_panel,
]

linkpage_panels = [
    MultiFieldPanel([
Esempio n. 11
0
class Taxes(models.Model):
    TAX_OF_FIELD = [
        ('sales', 'Ventas'),
        ('purchases', 'Compras'),
        ('neither', 'Ninguno'),
    ]
    CAL_OF_TAX = [
        # ('group', 'Grupo de impuestos'),
        ('fixed', 'Monto fijo en precio'),
        ('percent', 'Porcentaje en precio'),
    ]
    name = models.CharField(verbose_name=_("Nombre del impuesto"),
                            max_length=255,
                            null=True,
                            blank=True)
    tax_field = models.CharField(verbose_name=_('Ámbito del impuesto'),
                                 max_length=255,
                                 default='sales',
                                 choices=TAX_OF_FIELD)
    tax_calculation = models.CharField(verbose_name=_('Cálculo de impuesto'),
                                       max_length=255,
                                       default='percent',
                                       choices=CAL_OF_TAX)
    amount_of = models.FloatField(verbose_name=_('Importe'), default=0.0)
    include_in_price = models.BooleanField(
        verbose_name=_('Incluir en el precio'), default=True)
    subsequent_taxable = models.BooleanField(
        verbose_name=_('Base imponible subsecuente'), default=False)
    apply_to_variants = models.BooleanField(
        verbose_name=_('Aplicar impuesto a variantes'), default=False)

    panels = [
        MultiFieldPanel([
            FieldPanel('name'),
            FieldPanel('tax_field'),
            FieldPanel('tax_calculation'),
            FieldPanel('amount_of'),
            FieldPanel('include_in_price'),
            FieldPanel('subsequent_taxable'),
            FieldPanel('apply_to_variants'),
        ],
                        heading="Información general"),
        # MultiFieldPanel([
        #     InlinePanel('group_tax_rel'),
        # ], heading="Grupo de impuestos"),
    ]

    def __str__(self):
        return self.name

    class Meta:
        abstract = True


#
# # Lodgings relationships
# class AbsTaxes(Orderable, Taxes):
#     page = ParentalKey('accounting.Taxes', related_name='abstaxes_group')
#
#
# class GroupTaxRel(models.Model):
#     taxes = ParentalKey('Taxes', related_name='group_tax_rel')
#     group_tax = models.ForeignKey(
#         'AbsTaxes',
#         null=True,
#         blank=True,
#         on_delete=models.SET_NULL,
#         related_name="+"
#     )
#
#     panels = [
#         SnippetChooserPanel('group_tax')
#     ]
Esempio n. 12
0
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )

    search_fields = Page.search_fields + [
        index.SearchField('first_name'),
        index.SearchField('last_name'),
        index.SearchField('intro'),
        index.SearchField('biography'),
    ]

PersonPage.content_panels = [
    FieldPanel('title', classname="full title"),
    FieldPanel('first_name'),
    FieldPanel('last_name'),
    FieldPanel('intro', classname="full"),
    FieldPanel('biography', classname="full"),
    ImageChooserPanel('image'),
    MultiFieldPanel(ContactFields.panels, "Contact"),
    InlinePanel('related_links', label="Related links"),
]

PersonPage.promote_panels = Page.promote_panels + [
    ImageChooserPanel('feed_image'),
]

# Standard Page
Esempio n. 13
0
class Article(Page):
    authors = M2MField("author.Author", related_name="articles_by_author")
    translators = M2MField("author.Author",
                           related_name="translations_by_author",
                           blank=True)
    strap = models.TextField(blank=True)
    content = RichTextField(blank=True, verbose_name="Content - Deprecated. Use 'MODULAR CONTENT' instead.")
    modular_content = StreamField([
        ('paragraph', ParagraphBlock()),
        ('n_column_paragraph', NColumnParagraphBlock()),
        ('paragraph_with_map', ParagraphWithMapBlock()),
        ('paragraph_with_page', ParagraphWithPageBlock()),

        ('paragraph_with_quote', ParagraphWithBlockQuoteBlock()),
        ('full_width_quote', FullWidthBlockQuote()),
        ('video_with_quote', VideoWithQuoteBlock()),

        ('image_with_quote_and_paragraph', ImageWithQuoteAndParagraphBlock()),
        ('full_width_image', FullWidthImageBlock()),
        ('columnar_image_with_text', NColumnImageWithTextBlock()),

        ('full_width_embed', FullWidthEmbedBlock()),
        ('paragraph_with_embed', ParagraphWithEmbedBlock()),
        ('paragraph_with_raw_embed', ParagraphWithRawEmbedBlock()),

    ], null=True, blank=True)
    show_modular_content = models.BooleanField(default=False)
    language = models.CharField(max_length=7, choices=settings.LANGUAGES)
    original_published_date = models.DateField(null=True, blank=True)
    show_day = models.BooleanField(default=True)
    show_month = models.BooleanField(default=True)
    show_year = models.BooleanField(default=True)
    featured_image = models.ForeignKey('core.AffixImage',
                                       null=True, blank=True,
                                       on_delete=models.SET_NULL)
    show_featured_image = models.BooleanField(default=True)

    categories = M2MField("category.Category", related_name="articles_by_category")
    locations = M2MField("location.Location", related_name="articles_by_location", blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('strap'),
        M2MFieldPanel('authors'),
        M2MFieldPanel('translators'),
        FieldPanel('language'),
        MultiFieldPanel(
            [
                FieldPanel('original_published_date'),
                FieldRowPanel(
                    [
                        FieldPanel('show_day',classname="col4"),
                        FieldPanel('show_month',classname="col4"),
                        FieldPanel('show_year',classname="col4")
                    ])
            ],'Date'),
        FieldPanel('content'),
        MultiFieldPanel(
            [
                ImageChooserPanel('featured_image'),
                FieldPanel('show_featured_image'),
            ], 'Cover Image'),
        FieldPanel('categories'),
        M2MFieldPanel('locations'),
    ]

    search_fields = Page.search_fields + [
        index.SearchField('title', partial_match=True, boost=SearchBoost.TITLE),
        index.SearchField('get_authors', partial_match=True, boost=SearchBoost.AUTHOR),
        index.SearchField('translators', partial_match=True, boost=SearchBoost.AUTHOR),
        index.SearchField('strap', partial_match=True, boost=SearchBoost.DESCRIPTION),
        index.SearchField('content', partial_match=True, boost=SearchBoost.CONTENT),
        index.SearchField('modular_content', partial_match=True, boost=SearchBoost.CONTENT),
        index.SearchField('get_district_from_location', partial_match=True, boost=SearchBoost.LOCATION),
        index.SearchField('language', partial_match=True),
        index.FilterField('categories'),
        index.FilterField('language'),
        index.FilterField('get_search_type'),
        index.FilterField('get_categories'),
        index.FilterField('get_minimal_locations'),
        index.FilterField('get_authors_or_photographers'),
        index.FilterField('title'),
        index.FilterField('get_state_from_locations')
    ]

    def __str__(self):
        return self.title

    def get_authors(self):
        return [author.name for author in self.authors.all()]

    def get_authors_or_photographers(self):
        return self.get_authors()

    def get_district_from_location(self):
        return [location.address for location in self.locations.all()]

    def get_minimal_locations(self):
        return [location.minimal_address for location in self.locations.all()]

    def get_state_from_locations(self):
        return [location.state for location in self.locations.all()]

    def get_context(self, request, *args, **kwargs):
        try:
            site = Site.objects.get(hostname=request.get_host())
        except Site.DoesNotExist:
            site = Site.objects.filter(is_default_site=True)[0]
        return {
            'article': self,
            'request': request,
            'site': site
        }

    def get_absolute_url(self):
        name = "article-detail"
        return reverse(name, kwargs={"slug": self.slug})

    def get_translation(self):
        return get_translations_for_page(self)

    # Elastic search related methods
    def get_search_type(self):
        categories = [category.name for category in self.categories.all()]

        if 'VideoZone' in categories:
            return 'video'
        elif 'AudioZone' in categories:
            return 'audio'
        else:
            return 'article'

    def get_categories(self):
        return [category.name for category in self.categories.all()]

    def related_articles(self):
        if not self.pk:
            # In preview mode
            return []

        max_results = getattr(settings, "MAX_RELATED_RESULTS", 4)
        es_backend = get_search_backend()
        mapping = ElasticSearchMapping(self.__class__)

        minimal_locations = ""
        if (self.get_minimal_locations()):
            minimal_locations = self.get_minimal_locations()

        state_locations = ""
        if (self.get_state_from_locations()):
            state_locations = self.get_state_from_locations()

        authors_of_article = ""

        if self.authors:
            for author in self.authors.all():
                authors_of_article += author.name

        query = {
            "track_scores": "true",
            "query": {
                "bool": {
                    "must": [
                        {"match": {"language": self.language}},
                        {"term": {"live_filter": "true"}}
                    ],
                    "must_not": [
                        {"term": {"title_filter": self.title}}

                    ],
                    "should": [
                        {
                            "multi_match": {
                                "fields": "get_authors_or_photographers_filter",
                                "query": ["" + authors_of_article + ""]
                            }

                        },
                        {
                            "multi_match": {
                                "fields": "get_authors",
                                "query": ["" + authors_of_article + ""]
                            }

                        },
                        {
                            "multi_match": {
                                "fields": "get_minimal_locations_filter",
                                "query":minimal_locations
                            }
                        },
                        {
                            "multi_match":{
                                "fields":"get_state_from_locations_filter",
                                "query":state_locations
                            }

                        },
                        {
                            "match":{
                                "title":self.title
                            }
                        }
                    ],
                    "minimum_should_match": 1
                }
            },
            "sort": [
                {"_score": {"order": "desc"}},
                {"get_authors":{"order": "desc"}},
                {"first_published_at_filter": "desc"}
            ]
        }


        try:
            mlt = es_backend.es.search(
                index=es_backend.index_name,
                doc_type=mapping.get_document_type(),
                body=query
            )
        except ConnectionError:
            return []
        # Get pks from results
        pks = [hit['_source']['pk'] for hit in mlt['hits']['hits']][:max_results]

        # Initialise results dictionary
        results = dict((str(pk), None) for pk in pks)

        # Find objects in database and add them to dict
        queryset = self._default_manager.filter(pk__in=pks)
        for obj in queryset:
            results[str(obj.pk)] = obj

        # Return results in order given by ElasticSearch
        return [results[str(pk)] for pk in pks if results[str(pk)]]
Esempio n. 14
0
        }


        try:
            mlt = es_backend.es.search(
                index=es_backend.index_name,
                doc_type=mapping.get_document_type(),
                body=query
            )
        except ConnectionError:
            return []
        # Get pks from results
        pks = [hit['_source']['pk'] for hit in mlt['hits']['hits']][:max_results]

        # Initialise results dictionary
        results = dict((str(pk), None) for pk in pks)

        # Find objects in database and add them to dict
        queryset = self._default_manager.filter(pk__in=pks)
        for obj in queryset:
            results[str(obj.pk)] = obj

        # Return results in order given by ElasticSearch
        return [results[str(pk)] for pk in pks if results[str(pk)]]


if settings.MODULAR_ARTICLE:
    Article.content_panels.insert(-4, MultiFieldPanel([FieldPanel('show_modular_content')],
                                                      'Want to show modular content ?'))
    Article.content_panels.insert(-5, StreamFieldPanel('modular_content'))
Esempio n. 15
0
    body = StreamField([
        ('HTML', HtmlBlock()),
        ('WYSIWYG', WysiwygBlock()),
        ('Row', RowBlock()),
        ('Hero', HeroDonateBlock()),
        ('Hero_CTA', HeroCallToActionBlock()),
    ],
                       null=True,
                       blank=True)

    class Meta:
        verbose_name = "Donation Page"


DonatePage.content_panels = [
    FieldPanel('title', classname="full title"),
    FieldPanel('title_text', classname="full"),
    StreamFieldPanel('body'),
]


class HomePage(Page):
    title_text = RichTextField(null=True, blank=True)
    feed_image = models.ForeignKey(
        Image,
        help_text="An optional image to represent the page",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+')
    body = StreamField([
Esempio n. 16
0
class Main(AbstractForm):
    banner = RichTextField(blank=True,
                           help_text="Banner at the top of every page")
    banner_button_1_text = TextField(blank=True,
                                     help_text="Text for first button")
    banner_button_1_link = models.ForeignKey('wagtailcore.Page',
                                             null=True,
                                             blank=True,
                                             on_delete=models.SET_NULL,
                                             related_name='+')
    banner_button_2_text = TextField(blank=True,
                                     help_text="Text for second button")
    banner_button_2_link = models.ForeignKey('wagtailcore.Page',
                                             null=True,
                                             blank=True,
                                             on_delete=models.SET_NULL,
                                             related_name='+')
    header = TextField(blank=True, help_text="Hero title")
    body = RichTextField(blank=True, help_text="Description of page")
    filter_label_1 = TextField(
        blank=True, help_text="Label/Question for first set of filters")
    filter_label_2 = TextField(
        blank=True, help_text="Label/Question for second set of filters")
    filter_label_3 = TextField(
        blank=True, help_text="Label/Question for third set of filters")
    lookingfor = RichTextField(blank=True,
                               help_text="""
        Information on how to leave suggestions and what they are for
        """)
    alpha = RichTextField(blank=True, help_text="What is Alpha")
    alphatext = RichTextField(blank=True,
                              help_text="Why to take part in the alpha")
    hero_image = models.ForeignKey('wagtailimages.Image',
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   related_name='+',
                                   help_text="""
            Max file size: 10MB. Choose from: GIF, JPEG, PNG
            (but pick PNG if you have the choice)
        """)

    content_panels = AbstractForm.content_panels + [
        MultiFieldPanel([
            FieldPanel('banner', classname="full"),
            FieldPanel('banner_button_1_text', classname="full"),
            FieldPanel('banner_button_1_link', classname="full"),
            FieldPanel('banner_button_2_text', classname="full"),
            FieldPanel('banner_button_2_link', classname="full"),
        ],
                        heading="Banner"),
        ImageChooserPanel('hero_image'),
        InlinePanel('location_images', label="Location Images"),
        FieldPanel('header', classname="full"),
        FieldPanel('body', classname="full"),
        InlinePanel('project_info_block', label="Project Info Block"),
        MultiFieldPanel([
            FieldPanel('filter_label_1', classname="full"),
            FieldPanel('filter_label_2', classname="full"),
            FieldPanel('filter_label_3', classname="full")
        ]),
        FieldPanel('lookingfor', classname="full"),
        InlinePanel('form_fields', label="Form fields"),
        InlinePanel('high_lights', label="High Lights"),
        InlinePanel('footer_blocks', label="Footer Blocks"),
        InlinePanel('site_map', label="SiteMap"),
        InlinePanel('footer_links', label="Footer"),
    ]

    def get_context(self, request, **kwargs):
        context = super(Main, self).get_context(request)
        if 'ldmw_location_zipcode' in request.COOKIES:
            try:
                zipcode = request.COOKIES['ldmw_location_zipcode']
                for loc_img in MainLocationImages.objects.all():
                    short_zip = loc_img.first_letters_of_zip
                    if zipcode[:len(short_zip)] == short_zip:
                        location_hero_image = loc_img.location_image
                        break
                if not location_hero_image:
                    location_hero_image = self.hero_image
                context['hero_image'] = location_hero_image
            except:
                context['hero_image'] = self.hero_image
        else:
            context['hero_image'] = self.hero_image
        return context

    def process_form_submission(self, request_dict):
        return custom_form_submission(self, request_dict)

    def serve(self, request, *args, **kwargs):
        return custom_serve(**locals())
Esempio n. 17
0
        paginator = Paginator(blogs, 10)  # Show 10 blogs per page
        try:
            blogs = paginator.page(page)
        except PageNotAnInteger:
            blogs = paginator.page(1)
        except EmptyPage:
            blogs = paginator.page(paginator.num_pages)

        # Update template context
        context = super(BlogIndexPage, self).get_context(request)
        context['blogs'] = blogs
        return context


BlogIndexPage.content_panels = [
    FieldPanel('title', classname="full title"),
    FieldPanel('intro', classname="full"),
    InlinePanel(BlogIndexPage, 'related_links', label="Related links"),
]

BlogIndexPage.promote_panels = Page.promote_panels

# Blog page


class BlogPageCarouselItem(Orderable, CarouselItem):
    page = ParentalKey('blog.BlogPage', related_name='carousel_items')


class BlogPageRelatedLink(Orderable, RelatedLink):
    page = ParentalKey('blog.BlogPage', related_name='related_links')
Esempio n. 18
0
class FieldPanelPage(WagtailPage):
    name = models.CharField(max_length=50)

    content_panels = [
        FieldPanel('name'),
    ]
Esempio n. 19
0
class MultilingualMenuPage(MenuPage):
    title_de = models.CharField(
        verbose_name='title (de)',
        blank=True,
        max_length=255,
    )
    title_fr = models.CharField(
        verbose_name='title (fr)',
        blank=True,
        max_length=255,
    )
    repeated_item_text_de = models.CharField(
        verbose_name='repeated item link text (de)',
        blank=True,
        max_length=255,
    )
    repeated_item_text_fr = models.CharField(
        verbose_name='repeated item link text (fr)',
        blank=True,
        max_length=255,
    )
    translated_title = TranslatedField('title', 'title_de', 'title_fr')
    translated_repeated_item_text = TranslatedField(
        'repeated_item_text',
        'repeated_item_text_de',
        'repeated_item_text_fr',
    )

    class Meta:
        abstract = True

    def modify_submenu_items(self, menu_items, current_page,
                             current_ancestor_ids, current_site,
                             allow_repeating_parents, apply_active_classes,
                             original_menu_tag, menu_instance, request):
        return super(MultilingualMenuPage, self).modify_submenu_items(
            menu_items, current_page, current_ancestor_ids, current_site,
            allow_repeating_parents, apply_active_classes, original_menu_tag,
            menu_instance, request)

    def has_submenu_items(self, current_page, allow_repeating_parents,
                          original_menu_tag, menu_instance, request):
        return super(MultilingualMenuPage,
                     self).has_submenu_items(current_page,
                                             allow_repeating_parents,
                                             original_menu_tag, menu_instance,
                                             request)

    def get_repeated_menu_item(self, current_page, current_site,
                               apply_active_classes, original_menu_tag,
                               request):
        item = super(MultilingualMenuPage,
                     self).get_repeated_menu_item(current_page, current_site,
                                                  apply_active_classes,
                                                  original_menu_tag, request)
        item.text = self.translated_repeated_item_text or self.translated_title
        return item

    settings_panels = [
        PublishingPanel(),
        MultiFieldPanel(heading="Advanced menu behaviour",
                        classname="collapsible collapsed",
                        children=(
                            FieldPanel('repeat_in_subnav'),
                            FieldPanel('repeated_item_text'),
                            FieldPanel('repeated_item_text_de'),
                            FieldPanel('repeated_item_text_fr'),
                        ))
    ]
Esempio n. 20
0
class FieldPanelSnippet(models.Model):
    name = models.CharField(max_length=10)

    panels = [FieldPanel('name')]
Esempio n. 21
0
class AbstractFobiFormPage(Page):
    """An abstract Fobi form page.

    Pages implementing a Fobi form should inherit from it.

    :property fobi.models.FormEntry form_entry: Form entry to be rendered.
    """

    form_entry = models.ForeignKey('fobi.FormEntry',
                                   verbose_name=_("Form"),
                                   on_delete=models.PROTECT)

    form_template_name = models.CharField(
        _("Form template name"),
        max_length=255,
        null=True,
        blank=True,
        choices=get_form_template_choices(),
        help_text=_(
            "Choose an alternative template to render the form with. Leave "
            "blank to use the default for this page type (e.g. "
            "fobi_form_page.html)."))

    hide_form_title = models.BooleanField(
        _("Hide form title"),
        default=False,
        help_text=_("If checked, no form title is shown."))

    form_title = models.CharField(
        _("Form title"),
        max_length=255,
        null=True,
        blank=True,
        help_text=_("Overrides the default form title."))

    form_submit_button_text = models.CharField(
        _("Submit button text"),
        max_length=255,
        null=True,
        blank=True,
        help_text=_("Overrides the default form submit button text."))

    success_page_template_name = models.CharField(
        _("Success page template name"),
        max_length=255,
        null=True,
        blank=True,
        choices=get_success_page_template_choices(),
        help_text=_(
            "Choose an alternative template to render the success page with. "
            "Leave blank to use the default for this page type (e.g. "
            "fobi_form_page_success.html)."))

    hide_success_page_title = models.BooleanField(
        _("Hide success page title"),
        default=False,
        help_text=_("If checked, no success page title is shown."))

    success_page_title = models.CharField(
        _("Success page title"),
        max_length=255,
        null=True,
        blank=True,
        help_text=_("Overrides the default success page title."))

    success_page_text = models.TextField(
        _("Success page text"),
        null=True,
        blank=True,
        help_text=_("Overrides the default success page text."))

    form_page_panels = [
        FieldPanel('hide_form_title'),
        FieldPanel('form_title'),
        FieldPanel('form_entry'),
        FieldPanel('form_submit_button_text'),
    ]

    if get_form_template_choices():
        form_page_panels.append(FieldPanel('form_template_name'))

    success_page_panels = [
        FieldPanel('hide_success_page_title'),
        FieldPanel('success_page_title'),
        FieldPanel('success_page_text'),
    ]

    if get_success_page_template_choices():
        success_page_panels.append(FieldPanel('success_page_template_name'))

    content_panels = Page.content_panels + [
        MultiFieldPanel(form_page_panels, heading=_('Form page')),
        MultiFieldPanel(success_page_panels, heading=_('Success page')),
    ]

    preview_modes = [
        ('form', _('Form page')),
        ('success', _('Success page')),
    ]

    class Meta(object):
        """Meta options."""

        verbose_name = _('Fobi form page')
        verbose_name_plural = _('Fobi form pages')
        abstract = True

    def __init__(self, *args, **kwargs):
        super(AbstractFobiFormPage, self).__init__(*args, **kwargs)

        # Some wagtail magic...
        if not hasattr(self, 'form_template'):
            name, ext = os.path.splitext(self.template)
            self.form_template = name + '_form' + ext

        if not hasattr(self, 'success_template'):
            name, ext = os.path.splitext(self.template)
            self.success_template = name + '_form_success' + ext

    def get_form_template(self, request):
        """Get an alternative template name.

        Get an alternative template name from the object's
        ``form_template_name`` field, or the ``form_template`` attr defined on
        the page type model.

        :param django.http.HttpRequest request:
        """
        return self.form_template_name or self.form_template

    def get_success_template(self, request):
        """Get an alternative template name.

        Get an alternative template name from the object's
        ``success_page_template_name`` field, or the ``success_template`` attr
        defined on the page type model.

        :param django.http.HttpRequest request:
        """
        return self.success_page_template_name or self.success_template

    def serve(self, request, *args, **kwargs):
        """Serve the page using the ``FobiFormProcessor``."""
        fobi_form_processor = FobiFormProcessor()
        response = fobi_form_processor.process(request, instance=self)

        if response:
            return response

        # TODO: Returning HttpResponse seems dirty. See if it can be
        # replaced with TemplateResponse.
        return HttpResponse(fobi_form_processor.rendered_output)

    def serve_preview(self, request, mode):
        """Serve the page in Wagtail's 'preview' mode."""
        if mode == 'success':
            fobi_form_processor = FobiFormProcessor()

            # TODO: Returning HttpResponse seems dirty. See if it can be
            # replaced with TemplateResponse.
            return HttpResponse(
                fobi_form_processor.show_thanks_page(request, self))
        else:
            return super(AbstractFobiFormPage,
                         self).serve_preview(request, mode)
Esempio n. 22
0
class Section(models.Model):
    label = models.CharField(max_length=255, blank=True)
    title = models.CharField(max_length=255, blank=True)
    contents = models.TextField(blank=True)
    subpart = models.ForeignKey(Subpart, related_name="sections")
    sortable_label = models.CharField(max_length=255)

    panels = [
        FieldPanel('label'),
        FieldPanel('subpart'),
        FieldPanel('title'),
        FieldPanel('contents', classname="full"),
    ]

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['sortable_label']

    def extract_graphs(self):
        """Break out and store a section's paragraphs for indexing."""
        part = self.subpart.version.part
        section_tag = "{}-{}".format(part.part_number, self.label)
        extractor = regdown.extract_labeled_paragraph
        paragraph_ids = re.findall(r'[^{]*{(?P<label>[\w\-]+)}', self.contents)
        created = 0
        deleted = 0
        kept = 0
        exclude_from_deletion = []
        known_ids = []
        dupes = []
        for pid in paragraph_ids:
            raw_graph = extractor(pid, self.contents, exact=True)
            markup_graph = regdown.regdown(raw_graph)
            index_graph = strip_tags(markup_graph).strip()
            full_id = "{}-{}".format(section_tag, pid)
            graph, cr = SectionParagraph.objects.get_or_create(
                paragraph=index_graph,
                paragraph_id=pid,
                section=self)
            if cr:
                created += 1
            else:
                if full_id in known_ids:
                    dupes.append(full_id)
                else:
                    known_ids.append(full_id)
                    kept += 1
            exclude_from_deletion.append(graph.pk)
        to_delete = SectionParagraph.objects.filter(
            section__subpart__version__part=part,
            section__label=self.label).exclude(
            pk__in=exclude_from_deletion)
        deleted += to_delete.count()
        for graph in to_delete:
            graph.delete()
        dupes = sorted(set(dupes))
        return {
            'section': section_tag,
            'created': created,
            'deleted': deleted,
            'kept': kept,
            'dupes': dupes,
        }

    def save(self, **kwargs):
        self.sortable_label = '-'.join(sortable_label(self.label))
        super(Section, self).save(**kwargs)

    @cached_property
    def part(self):
        return self.subpart.version.part.part_number

    @property
    def section_number(self):
        return self.label

    @property
    def numeric_label(self):
        if self.label.isdigit():
            return '\xa7\xa0{}.{}'.format(self.part, int(self.label))
        else:
            return ''

    @property
    def title_content(self):
        if self.numeric_label:
            return self.title.replace(self.numeric_label, '').strip()
        else:
            return self.title
Esempio n. 23
0
class Logo(models.Model):
    class Meta:
        verbose_name_plural = _('logos')

    CATEGORY_CHOICES = (
        ('committee', _('Committee')),
        ('section', _('Section')),
    )

    category = models.CharField(
        max_length=20,
        choices=CATEGORY_CHOICES,
        verbose_name=_('category'),
        blank=False,
        null=False,
    )

    link = models.URLField(
        verbose_name=_('links to'),
        null=False,
        blank=False,
    )

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

    logo_white = models.ForeignKey('wagtailimages.Image',
                                   verbose_name=_('white logo'),
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   related_name='+')

    logo_black = models.ForeignKey('wagtailimages.Image',
                                   verbose_name=_('black logo'),
                                   null=True,
                                   blank=True,
                                   on_delete=models.SET_NULL,
                                   related_name='+')

    belongs_to = models.ForeignKey(
        'wagtailcore.Site',
        verbose_name=_('belongs to'),
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
    )

    # ------ Administrator settings ------
    panels = [
        MultiFieldPanel([
            FieldRowPanel([
                FieldPanel('category'),
                FieldPanel('link'),
            ]),
            ImageChooserPanel('logo'),
            ImageChooserPanel('logo_white'),
            ImageChooserPanel('logo_black'),
            FieldPanel('belongs_to'),
        ])
    ]
Esempio n. 24
0
class HomePage(RoutablePageMixin, Page):
    """
    Home page for standard pages.
    We need to alter the page model's context to return the child page objects,
    the StandardPage objects, so that it works as an index page
    RoutablePageMixin is used to allow for a custom sub-URL for the tag views
    defined above.
    """
    tag_line = models.CharField(max_length=148)

    content_panels = Page.content_panels + [
        FieldPanel('tag_line', classname="full"),
    ]

    # Speficies that only StandardPage objects can live under the home page
    subpage_types = ['StandardPage', 'LegendaryItem']

    # Defines a method to access the children of the page (e.g. StandardPage objects).
    def children(self):
        return self.get_children().specific().live()

    # Overrides the context to list all child items, that are live, by the
    # date that they were published
    def get_context(self, request):
        # Get posts
        posts = StandardPage.objects.descendant_of(self).live().order_by(
            '-updated')
        latest_posts = StandardPage.objects.descendant_of(
            self).live().order_by('-updated')
        # Pagination
        page = request.GET.get('page')
        paginator = Paginator(posts, 3)  # Show 3 posts per page
        try:
            posts = paginator.page(page)
        except PageNotAnInteger:
            posts = paginator.page(1)
        except EmptyPage:
            posts = paginator.page(paginator.num_pages)

        context = super(HomePage, self).get_context(request)
        context['posts'] = posts
        context['latest_posts'] = latest_posts
        return context

    # This defines a Custom view that utilizes Tags. This view will return all
    # related StandardPages for a given Tag or redirect back to the HomePage.
    # More information on RoutablePages is at
    # http://docs.wagtail.io/en/latest/reference/contrib/routablepage.html
    @route('^home/tags/$', name='tag_archive')
    @route('^home/tags/(\w+)/$', name='tag_archive')
    def tag_archive(self, request, tag=None):

        try:
            tag = Tag.objects.get(slug=tag)
        except Tag.DoesNotExist:
            if tag:
                msg = 'There are no posts tagged with "{}"'.format(tag)
                messages.add_message(request, messages.INFO, msg)
            return redirect(self.url)

        posts = self.get_posts(tag=tag)
        context = {'tag': tag, 'posts': posts}
        return render(request, 'home/home_page.html', context)

    def serve_preview(self, request, mode_name):
        # Needed for previews to work
        return self.serve(request)

    # Returns the child StandardPage objects for this HomePage.
    # If a tag is used then it will filter the posts by tag.
    def get_posts(self, tag=None):
        posts = StandardPage.objects.live().descendant_of(self)
        if tag:
            posts = posts.filter(tags=tag)
        return posts

    # Returns the list of Tags for all child posts of this StandardPage.
    def get_child_tags(self):
        tags = []
        for post in self.get_posts():
            # Not tags.append() because we don't want a list of lists
            tags += post.get_tags
        tags = sorted(set(tags))
        return tags
Esempio n. 25
0
class BreadPage(Page):
    """
    Detail view for a specific bread
    """
    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
    )
    origin = models.ForeignKey(
        Country,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )

    # We include related_name='+' to avoid name collisions on relationships.
    # e.g. there are two FooPage models in two different apps,
    # and they both have a FK to bread_type, they'll both try to create a
    # relationship called `foopage_objects` that will throw a valueError on
    # collision.
    bread_type = models.ForeignKey(
        'breads.BreadType',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )
    ingredients = ParentalManyToManyField('BreadIngredient', blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('introduction', classname="full"),
        ImageChooserPanel('image'),
        StreamFieldPanel('body'),
        FieldPanel('origin'),
        FieldPanel('bread_type'),
        MultiFieldPanel(
            [
                FieldPanel(
                    'ingredients',
                    widget=forms.CheckboxSelectMultiple,
                ),
            ],
            heading="Additional Metadata",
            classname="collapsible collapsed"
        ),
    ]

    search_fields = Page.search_fields + [
        index.SearchField('title'),
        index.SearchField('body'),
    ]

    parent_page_types = ['BreadsIndexPage']
Esempio n. 26
0
class NavigationMenuManager(models.Manager):
    def get_by_natural_key(self, name):
        return self.get(menu_name=name)


@register_snippet
class NavigationMenu(ClusterableModel):
    objects = NavigationMenuManager()
    menu_name = models.CharField(max_length=255, null=False, blank=False)

    def __str__(self):
        return self.menu_name


NavigationMenu.panels = [
    FieldPanel('menu_name', classname='full title'),
    InlinePanel('menu_items', label="Menu Items"),
]

# Service Price Snippet


@register_snippet
class ServicePrice(models.Model):
    title = models.CharField(max_length=50)
    body = models.TextField()
    price = models.DecimalField(max_digits=5, decimal_places=2)

    panels = [
        FieldPanel('title'),
        FieldPanel('body'),
Esempio n. 27
0
class JobListingPage(CFGOVPage):
    description = RichTextField('Summary')
    open_date = models.DateField('Open date')
    close_date = models.DateField('Close date')
    salary_min = models.DecimalField('Minimum salary',
                                     max_digits=11,
                                     decimal_places=2)
    salary_max = models.DecimalField('Maximum salary',
                                     max_digits=11,
                                     decimal_places=2)
    division = models.ForeignKey(JobCategory,
                                 on_delete=models.PROTECT,
                                 null=True)
    job_length = models.ForeignKey(JobLength,
                                   on_delete=models.PROTECT,
                                   null=True,
                                   verbose_name="Position length",
                                   blank=True)
    service_type = models.ForeignKey(ServiceType,
                                     on_delete=models.PROTECT,
                                     null=True,
                                     blank=True)
    location = models.ForeignKey(JobLocation,
                                 related_name='job_listings',
                                 on_delete=models.PROTECT)
    allow_remote = models.BooleanField(
        default=False,
        help_text='Adds remote option to jobs with office locations.',
        verbose_name="Location can also be remote")
    responsibilities = RichTextField('Responsibilities', null=True, blank=True)
    travel_required = models.BooleanField(
        blank=False,
        default=False,
        help_text=('Optional: Check to add a "Travel required" section to the '
                   'job description. Section content defaults to "Yes".'))
    travel_details = RichTextField(
        null=True,
        blank=True,
        help_text='Optional: Add content for "Travel required" section.')
    additional_section_title = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        help_text='Optional: Add title for an additional section '
        'that will display at end of job description.')
    additional_section_content = RichTextField(
        null=True,
        blank=True,
        help_text='Optional: Add content for an additional section '
        'that will display at end of job description.')
    content_panels = CFGOVPage.content_panels + [
        MultiFieldPanel([
            FieldPanel('division', classname='full'),
            InlinePanel('grades', label='Grades'),
            FieldRowPanel([
                FieldPanel('open_date', classname='col6'),
                FieldPanel('close_date', classname='col6'),
            ]),
            FieldRowPanel([
                FieldPanel('salary_min', classname='col6'),
                FieldPanel('salary_max', classname='col6'),
            ]),
            FieldRowPanel([
                FieldPanel('service_type', classname='col6'),
                FieldPanel('job_length', classname='col6'),
            ]),
        ],
                        heading='Details'),
        MultiFieldPanel([
            FieldPanel('location', classname='full'),
            FieldPanel('allow_remote', classname='full'),
        ],
                        heading='Location'),
        MultiFieldPanel([
            FieldPanel('description', classname='full'),
            FieldPanel('responsibilities', classname='full'),
            FieldPanel('travel_required', classname='full'),
            FieldPanel('travel_details', classname='full'),
            FieldPanel('additional_section_title', classname='full'),
            FieldPanel('additional_section_content', classname='full'),
        ],
                        heading='Description'),
        InlinePanel('usajobs_application_links',
                    label='USAJobs application links'),
        InlinePanel('email_application_links',
                    label='Email application links'),
    ]

    edit_handler = TabbedInterface([
        ObjectList(content_panels, heading='Content'),
        ObjectList(CFGOVPage.settings_panels, heading='Configuration'),
    ])

    template = 'job-description-page/index.html'

    objects = PageManager()

    def get_context(self, request, *args, **kwargs):
        context = super(JobListingPage, self).get_context(request)
        try:
            context['about_us'] = ReusableText.objects.get(
                title='About us (For consumers)')
        except:
            pass
        if hasattr(self.location, 'region'):
            context['states'] = [
                state.abbreviation
                for state in self.location.region.states.all()
            ]
            context['location_type'] = 'region'
        else:
            context['states'] = []
            context['location_type'] = 'office'
        context['cities'] = self.location.cities.all()
        return context

    @property
    def page_js(self):
        return super(JobListingPage, self).page_js + ['read-more.js']

    @property
    def ordered_grades(self):
        """Return a list of job grades in numerical order.
        Non-numeric grades are sorted alphabetically after numeric grades.
        """
        grades = set(g.grade.grade for g in self.grades.all())
        return sorted(grades, key=lambda g: int(g) if g.isdigit() else g)
Esempio n. 28
0
    def get_form(self, *args, **kwargs):
        form_class = self.get_form_class()
        form_params = self.get_form_parameters()
        form_params.update(kwargs)

        return form_class(*args, **form_params)

    def process_form_submission(self, form):
        if self.store_submission:
            return FormSubmission.objects.create(form_data=json.dumps(
                form.cleaned_data, cls=DjangoJSONEncoder),
                                                 form=self)


if recaptcha_enabled():
    BaseForm.panels.insert(2, FieldPanel('add_recaptcha'))


class EmailForm(BaseForm):
    """
    A Form Page that sends email. Pages implementing a form to be send
    to an email should inherit from it
    """

    to_address = models.CharField(
        verbose_name=_('to address'),
        max_length=255,
        blank=True,
        help_text=_(
            "Optional - form submissions will be emailed to these addresses. Separate multiple addresses by comma."
        )  # NOQA
Esempio n. 29
0
class Person(ClusterableModel, index.Indexed):

    user = OneToOneField(User, null=True, blank=True,
                         on_delete=CASCADE, related_name='profile')
    first_name = CharField(max_length=255)
    middle_name = CharField(max_length=255, null=True, blank=True)
    last_name = CharField(max_length=255)
    bio = RichTextField(blank=True)

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

    position = CharField(max_length=140, blank=True)
    employer = CharField(max_length=140, blank=True)
    term = CharField(blank=True, max_length=9, help_text="Format:YYYY-YYYY")
    linked_in = URLField(blank=True)
    blog_url = URLField(blank=True)
    osf_profile = URLField(blank=True)
    google_plus = URLField(blank=True)
    github = URLField(blank=True)
    twitter = URLField(blank=True)
    phone_number = CharField(max_length=12, blank=True,
                             help_text="Format:XXX-XXX-XXXX")
    email_address = EmailField(blank=True)

    favorite_food = CharField(max_length=140, blank=True)

    tags = TaggableManager(through='common.PersonTag', blank=True)

    search_fields = [
        index.SearchField('first_name', partial_match=True),
        index.SearchField('last_name', partial_match=True),
        index.SearchField('middle_name', partial_match=True),
    ]

    panels = [
        MultiFieldPanel([
            FieldPanel('user'),
            FieldPanel('first_name'),
            FieldPanel('middle_name'),
            FieldPanel('last_name'),
            FieldPanel('bio'),
            FieldPanel('tags'),
            FieldPanel('position'),
            FieldPanel('employer'),
            FieldPanel('term'),
            FieldPanel('linked_in'),
            FieldPanel('blog_url'),
            FieldPanel('osf_profile'),
            FieldPanel('google_plus'),
            FieldPanel('github'),
            FieldPanel('twitter'),
            FieldPanel('phone_number'),
            FieldPanel('email_address'),
            FieldPanel('favorite_food'),
        ], heading='Basic Information'),
        ImageChooserPanel('photo'),
    ]

    class Meta:
        verbose_name_plural = "People"
        ordering = ['last_name']

    def __str__(self):
        return '{self.last_name}, {self.first_name}'.format(self=self)
Esempio n. 30
0
class BrowsePage(CFGOVPage):
    header = StreamField([
        ('text_introduction', molecules.TextIntroduction()),
        ('featured_content', organisms.FeaturedContent()),
    ],
                         blank=True)

    content = StreamField([
        ('full_width_text', organisms.FullWidthText()),
        ('info_unit_group', organisms.InfoUnitGroup()),
        ('expandable_group', organisms.ExpandableGroup()),
        ('expandable', organisms.Expandable()),
        ('well', organisms.Well()),
        ('video_player', organisms.VideoPlayer()),
        ('snippet_list', organisms.ResourceList()),
        ('table_block',
         organisms.AtomicTableBlock(table_options={'renderer': 'html'})),
        ('feedback', v1_blocks.Feedback()),
        ('raw_html_block', blocks.RawHTMLBlock(label='Raw HTML block')),
        ('conference_registration_form', ConferenceRegistrationForm()),
        ('chart_block', organisms.ChartBlock()),
        ('mortgage_chart_block', organisms.MortgageChartBlock()),
        ('mortgage_map_block', organisms.MortgageMapBlock()),
        ('mortgage_downloads_block', MortgageDataDownloads()),
        ('data_snapshot', organisms.DataSnapshot()),
        ('job_listing_table', JobListingTable()),
        ('bureau_structure', organisms.BureauStructure()),
    ],
                          blank=True)

    secondary_nav_exclude_sibling_pages = models.BooleanField(default=False)

    # General content tab
    content_panels = CFGOVPage.content_panels + [
        StreamFieldPanel('header'),
        StreamFieldPanel('content'),
    ]

    sidefoot_panels = CFGOVPage.sidefoot_panels + [
        FieldPanel('secondary_nav_exclude_sibling_pages'),
    ]

    # Tab handler interface
    edit_handler = TabbedInterface([
        ObjectList(content_panels, heading='General Content'),
        ObjectList(sidefoot_panels, heading='Sidebar'),
        ObjectList(CFGOVPage.settings_panels, heading='Configuration'),
    ])

    template = 'browse-basic/index.html'

    objects = PageManager()

    search_fields = CFGOVPage.search_fields + [
        index.SearchField('content'),
        index.SearchField('header')
    ]

    @property
    def page_js(self):
        return (super(BrowsePage, self).page_js + ['secondary-navigation.js'])

    def get_context(self, request, *args, **kwargs):
        context = super(BrowsePage, self).get_context(request, *args, **kwargs)
        context.update({'get_secondary_nav_items': get_secondary_nav_items})
        return context