コード例 #1
0
def information_overlay_trigger_button(
    context,
    position_offset_x=0,
    position_offset_y=0,
    position_type=None,
    information_overlay_slug=None,
    text=None
):
    u"""
    Build the context for the information_overlay_trigger_button inclusion tag.

    Args:
        context (RequestContext) (injected by decorator)

    Returns:
        dictionary: Template context
    """

    # ==============
    # === Render ===
    # ==============
    return render_to_string(
        'information_overlay_trigger_button.html',
        {
            'position_offset_x': position_offset_x,
            'position_offset_y': position_offset_y,
            'position_type': position_type,
            'information_overlay_slug': information_overlay_slug,
            'styles': get_styles('information_overlay_trigger_button'),
            'text': text,
        },
        context.request
    )
コード例 #2
0
def information_overlay(
    context,
    slug=None,
    text=None,
    title=None,
):
    u"""
    Build the context for the information_overlay inclusion tag.

    Args:
        context (RequestContext) (injected by decorator)

    Returns:
        dictionary: Template context
    """

    # ==============
    # === Render ===
    # ==============
    return render_to_string(
        'information_overlay.html', {
            'slug': slug,
            'styles': get_styles('information_overlay'),
            'text': text,
            'title': title,
        }, context.request)
コード例 #3
0
def home_showcase(context, item_type):
    u"""
    Build the context for the home_showcase inclusion tag.

    Args:
        context (RequestContext) (injected by decorator)

    Returns:
        dictionary: Template context
    """

    if item_type == 'prisoner':
        items = list((Prisoner.published_objects.filter(featured=True, )))

        title = pgettext(u'Home showcase (IPA prisoner)', u'Prisoner showcase')

    elif item_type == 'featured_news':
        items = list((FeaturedNews.published_objects.filter(
            language=context.request.LANGUAGE_CODE,
            featured=True,
        )))

        title = pgettext(u'Home showcase (AeA featured news)',
                         u'Featured news showcase')

    # ==============
    # === Render ===
    # ==============
    return render_to_string(
        'home_showcase.html', {
            'items': items,
            'item_type': item_type,
            'styles': get_styles('home_showcase'),
            'title': title,
        }, context.request)
コード例 #4
0
    def get(self, request, *args, **kwargs):
        head_image = (static('public/img/og_Intro_Screen_FB_2.png') +
                      '?v=2019-08-28')

        return render(
            request,
            'home.html',
            context=get_view_context_with_defaults(
                {
                    'head_image': head_image,
                    'styles': get_styles('home'),
                },
                request,
            ),
        )
コード例 #5
0
def home_showcase_item_prisoner(context, prisoner):
    u"""
    Build the context for the home_showcase_item_prisoner inclusion tag.

    Args:
        context (RequestContext) (injected by decorator)
        prisoner (Prisoner)

    Returns:
        dictionary: Template context
    """

    language_code = context.request.LANGUAGE_CODE

    prisoner_age = None
    prisoner_biography = None
    prisoner_country = None
    prisoner_ethnicity = None
    prisoner_name = None
    prisoner_picture_path = None
    prisoner_religion = None

    # --------------------
    # --- prisoner_age ---
    # --------------------

    try:
        prisoner_date_of_birth = date(
            prisoner.dob_year,
            prisoner.dob_month,
            prisoner.dob_day,
        )

        today_date = date.today()

        # Via https://stackoverflow.com/a/9754466/7949868
        prisoner_age = (today_date.year - prisoner_date_of_birth.year - (
            (today_date.month, today_date.day) <
            (prisoner_date_of_birth.month, prisoner_date_of_birth.day)))
    except TypeError:
        pass

    # --------------------------
    # --- prisoner_biography ---
    # --------------------------
    prisoner_biography = (prisoner.biography
                          if language_code == 'en' else prisoner.biography_fa)

    # ------------------------
    # --- prisoner_country ---
    # ------------------------
    prisoner_country = get_localized_choice_instance_name(
        prisoner.home_countries.first(), language_code)

    # --------------------------
    # --- prisoner_ethnicity ---
    # --------------------------
    prisoner_ethnicity = get_localized_choice_instance_name(
        prisoner.ethnicity, language_code)

    # ---------------------
    # --- prisoner_name ---
    # ---------------------
    prisoner_name = (u'{forename} {surname}'.format(
        forename=(getattr(
            prisoner,
            'forename_{language_code}'.format(language_code=language_code, ),
        ) or ''),
        surname=(getattr(
            prisoner,
            'surname_{language_code}'.format(language_code=language_code, ),
        ) or ''),
    ).strip())

    if prisoner_name == '':
        prisoner_name = pgettext(
            u'Home showcase (IPA prisoner)',
            # Translators: Used if prisoner has no forename and surname
            u'Name unknown')

    # -----------------------------
    # --- prisoner_picture_path ---
    # -----------------------------
    try:
        if (isinstance(prisoner.picture, ImageFieldFile)
                and type(prisoner.picture.url) in [str, unicode]):
            prisoner_picture_path = (get_thumbnailer(
                prisoner.picture).get_thumbnail({
                    'size': (200, 200)
                }).url)
    except ValueError:
        prisoner_picture_path = None

    if prisoner_picture_path is None:
        if prisoner.gender == 'M':
            prisoner_picture_path = (static('public/img/prisoner_male.png') +
                                     '?v=2019-08-28')
        elif prisoner.gender == 'F':
            prisoner_picture_path = (static('public/img/prisoner_female.png') +
                                     '?v=2019-08-28')

    # -------------------------
    # --- prisoner_religion ---
    # -------------------------
    prisoner_religion = get_localized_choice_instance_name(
        prisoner.religion, language_code)

    prisoner_url = ipa_reverse(
        'public:prisoner',
        p_pk=prisoner.id,
    )

    # -------------------------------
    # --- Construct prisoner_info ---
    # -------------------------------
    try:
        prisoner_info = PrisonerInfo(
            age=prisoner_age,
            biography=prisoner_biography,
            country=prisoner_country,
            ethnicity=prisoner_ethnicity,
            name=prisoner_name,
            picture_path=prisoner_picture_path,
            religion=prisoner_religion,
            url=prisoner_url,
        )
    except TypeError as error:
        logger.warning(
            'Didn’t display prisoner {prisoner_id} due to: {error}'.format(
                prisoner_id=prisoner.id,
                error=error,
            ))

        return ''

    # ==============
    # === Render ===
    # ==============
    return render_to_string(
        'home_showcase_item_prisoner.html', {
            'prisoner_info': prisoner_info,
            'styles': get_styles('home_showcase_item_prisoner'),
        }, context.request)
コード例 #6
0
def home_showcase_item_featured_news(
    context,
    featured_news
):
    u"""
    Build the context for the home_showcase_item_featured_news inclusion tag.

    Args:
        context (RequestContext) (injected by decorator)
        prisoner (Prisoner)

    Returns:
        dictionary: Template context
    """

    # -----------------------------
    # --- featured_news_title ---
    # -----------------------------
    featured_news_title = getattr(
        featured_news,
        'title',
        None
    )

    # -----------------------------
    # --- featured_news_excerpt ---
    # -----------------------------
    featured_news_excerpt = getattr(
        featured_news,
        'excerpt',
        None
    )

    # -------------------------------
    # --- featured_news_link ---
    # -------------------------------
    featured_news_link = getattr(
        featured_news,
        'link',
        None
    )

    # --------------------------------
    # --- featured_news_photo_path ---
    # --------------------------------
    featured_news_photo_path = (
        static('public/img/prison.png') + '?v=2019-08-28'
    )

    try:
        if (
            isinstance(featured_news.photo, ImageFieldFile) and
            type(featured_news.photo.url) in [str, unicode]
        ):
            featured_news_photo_path = featured_news.photo.url
    except ValueError:
        pass

    # ------------------------------------
    # --- Construct featured_news_info ---
    # ------------------------------------
    try:
        featured_news_info = FeaturedNewsInfo(
            excerpt=featured_news_excerpt,
            link=featured_news_link,
            photo_path=featured_news_photo_path,
            title=featured_news_title,
        )
    except TypeError as error:
        logger.warning(
            'Didn’t display featured news {featured_news_id} due to: {error}'.format(
                featured_news_id=featured_news.id,
                error=error,
            )
        )

        return ''

    # ==============
    # === Render ===
    # ==============
    return render_to_string(
        'home_showcase_item_featured_news.html',
        {
            'featured_news_info': featured_news_info,
            'styles': get_styles('home_showcase_item_featured_news'),
        },
        context.request
    )
コード例 #7
0
def nav_header(context):
    u"""
    Build the context for the nav_header inclusion tag.

    Args:
        context (RequestContext) (injected by decorator)

    Returns:
        dictionary: Template context
    """

    request = context.request

    primary_links = []

    if request.ipa_site == 'ipa':
        primary_links += (
            TextLink(
                href=ipa_reverse(
                    'public:prisoners',
                ),
                text=pgettext(
                    u'Navigation header',
                    # Translators: Prisoners page link
                    u'Prisoners'
                ),
            ),
        )

    primary_links += (
        TextLink(
            href=ipa_reverse(
                'public:prisons',
            ),
            text=pgettext(
                u'Navigation header',
                # Translators: Prisons page link
                u'Prisons'
            ),
        ),
        TextLink(
            href=ipa_reverse(
                'public:judges',
            ),
            text=pgettext(
                u'Navigation header',
                # Translators: Judges page link
                u'Judges'
            ),
        ),
        TextLink(
            href=u'https://prisonatlas.com/',
            text=pgettext(
                u'Navigation header',
                # Translators: Blog (prisonatlas.com) link
                u'Blog'
            ),
            is_external=True,
        ),
    )

    secondary_links = [
        TextLink(
            href=(
                {
                    'en': u'https://united4iran.org/en/act-now.html',
                    'fa': u'https://united4iran.org/fa/act-now.html',
                }[request.LANGUAGE_CODE]
            ),
            text=pgettext(
                u'Navigation header',
                # Translators: Act now (united4iran.org) link
                u'Act now'
            ),
            is_boxed=True,
        ),
        TextLink(
            href=ipa_reverse(
                'public:about',
            ),
            text=pgettext(
                u'Navigation header',
                # Translators: About page link
                u'About'
            ),
        ),
    ]

    if request.LANGUAGE_CODE == 'en':
        secondary_links += (
            TextLink(
                href=re.sub(
                    r'^\/en',
                    '/fa',
                    request.get_full_path(),
                ),
                text=u'فارسی',
            ),
        )
    elif request.LANGUAGE_CODE == 'fa':
        secondary_links += (
            TextLink(
                href=re.sub(
                    r'^\/fa',
                    '/en',
                    request.get_full_path(),
                ),
                text=u'English',
            ),
        )

    u"""
    GH 2019-08-28: The href replacement code is necessary since the hostname exposed to Django may not be the public hostname (depending on how our servers are configured).

    A previous iteration of this code simply replaced settings.IPA_HOSTNAME with settings.AEA_HOSTNAME (or vice versa), but if the hostname exposed to Django was e.g. 'api.ipa.foo.dev' and the AeA hostname was 'aea.foo.dev', the AeA link would end up being rendered as 'api.aea.foo.dev'.

    Also note that I used this regular expression approach since it seemed to be the cleanest way to retain the scheme, port, and path of the reversed homepage URL. e.g. If we decided to build the URL from scratch, AFAIK we’d need custom code to exclude the port from the URL if it was 80 or 443 (in production) while retaining an explicit port 8000 for the Django development server.
    """
    sister_site_link_info = TextLink(
        href=re.sub(
            r'^(?P<protocol>https?:\/\/)(?P<hostname>[\w\.]*)(?P<port_and_path>:?\d*\/.*)$',
            r'\g<protocol>{hostname}\g<port_and_path>'.format(
                hostname=(
                    {
                        'aea': settings.IPA_HOSTNAME,
                        'ipa': settings.AEA_HOSTNAME,
                    }.get(request.ipa_site, '')
                )
            ),
            request.build_absolute_uri(
                ipa_reverse('public:homepage')
            ),
        ),
        text=(
            {
                'aea': pgettext(
                    u'Navigation header',
                    # Translators: Boxed IPA link
                    u'Political prisoners'
                ),
                'ipa': pgettext(
                    u'Navigation header',
                    # Translators: Boxed AeA link
                    u'Non-political prisoners'
                ),
            }.get(request.ipa_site, '')
        )
    )

    should_show_sister_site_link = settings.SHOW_SISTER_SITE_LINK

    # ==============
    # === Render ===
    # ==============
    return render_to_string(
        'nav_header.html',
        {
            'links_segments': (
                primary_links,
                secondary_links,
            ),
            'should_show_sister_site_link': should_show_sister_site_link,
            'sister_site_link_info': sister_site_link_info,
            'styles': get_styles('nav_header'),
        },
        request
    )
コード例 #8
0
ファイル: home_nav_boxes.py プロジェクト: u4i-admin2/IPA
def home_nav_boxes(context):
    u"""
    Build the context for the home_nav_boxes inclusion tag.

    Args:
        context (RequestContext) (injected by decorator)

    Returns:
        dictionary: Template context
    """

    static_format_string = u'public/img/{file_name}'

    nav_box_infos = []

    entity_counts = get_entity_counts(context.request)

    # ==================
    # === Judges box ===
    # ==================
    nav_box_infos.append(
        NavBoxInfo(
            background_img_src=static_format_string.format(
                file_name=u'Judges-{site}.jpg'.format(
                    site=context.request.ipa_site
                )
            ),
            count=entity_counts.judge,
            description=pgettext(
                u'Home nav box',
                # Translators: Nav box description text (small text under divider)
                u'Click to explore the sentences handed down by some of Iran’s harshest judges'
            ),
            href=ipa_reverse(
                'public:judges',
            ),
            name=pgettext(
                u'Home nav box',
                # Translators: Nav box description title (large text beneath number)
                u'Judges'
            ),
        )
    )

    # =====================
    # === Prisoners box ===
    # =====================
    if context.request.ipa_site == 'ipa':
        nav_box_infos.append(
            NavBoxInfo(
                background_img_src=static_format_string.format(
                    file_name=u'Prisoners-{site}.jpg'.format(
                        site=context.request.ipa_site
                    )
                ),
                count=entity_counts.prisoner,
                description=pgettext(
                    u'Home nav box',
                    # Translators: Nav box description text (small text under divider)
                    u'Click to explore the lives and sentences of Iran’s political prisoners'
                ),
                href=ipa_reverse(
                    'public:prisoners',
                ),
                name=pgettext(
                    u'Home nav box',
                    # Translators: Nav box description title (large text beneath number)
                    u'Prisoners'
                ),
            )
        )

    # ==================
    # === Prison box ===
    # ==================
    nav_box_infos.append(
        NavBoxInfo(
            background_img_src=static_format_string.format(
                file_name=u'Prison-{site}.jpg'.format(
                    site=context.request.ipa_site
                )
            ),
            count=entity_counts.prison,
            description=pgettext(
                u'Home nav box',
                # Translators: Nav box description text (small text under divider)
                u'Click to explore the prisons that hold Iran’s political prisoners behind their bars'
            ),
            href=ipa_reverse(
                'public:prisons',
            ),
            name=pgettext(
                u'Home nav box',
                # Translators: Nav box description title (large text beneath number)
                u'Prisons'
            ),
        )
    )

    # ==============
    # === Render ===
    # ==============
    return render_to_string(
        'home_nav_boxes.html',
        {
            'nav_box_infos': nav_box_infos,
            'styles': get_styles('home_nav_boxes'),
        },
        context.request
    )