コード例 #1
0
# Copyright (c) 2013 by Pablo Martín <*****@*****.**>
#
# This software is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this software.  If not, see <http://www.gnu.org/licenses/>.
from django.template import Library

from inplaceeditform_bootstrap import settings as inplaceeditform_bootstrap_settings

register = Library()


def inplace_bootstrap_extra_options(context):
    return {
        'tooltip_text':
        inplaceeditform_bootstrap_settings.INPLACEEDIT_EDIT_TOOLTIP_TEXT,
    }


register.inclusion_tag("inplaceeditform_bootstrap/extra_options.html",
                       takes_context=True)(inplace_bootstrap_extra_options)
コード例 #2
0
ファイル: work_lib.py プロジェクト: XiaolongX99/HYCMES
        {% mywork user %}
    
    settings required::

        MIDDLEWARE_CLASSES = (
            'django.middleware.common.CommonMiddleware',
            ...
        )

    **Tip**

    this can be used instead, if *workitems* variable is available
    in the context::

        {% include "goflow/workitems.html" %}
    
    when using *render_to_response* shortcut, don't forget
    to add a *RequestContext* as following::

        def some_view(request):
        # ...
        return render_to_response('my_template.html',
                                  my_data_dictionary,
                                  context_instance=RequestContext(request))
    '''
    workitems = WorkItem.objects.list_safe(user=user, noauto=True)
    return {'workitems':workitems}
mywork = register.inclusion_tag("goflow/workitems.html")(mywork)

コード例 #3
0
ファイル: favourite.py プロジェクト: Yanual/ezwebplatform
# See license file (LICENSE.txt) for info about license terms.

from django import template
from django.core.urlresolvers import reverse
from django.conf import settings
from django.template import Context, Library, Template, Variable

from clms.models import Layout, FavouriteLayout

register = Library()


def favourite(context, user, layout, view):
    favourite_layout = FavouriteLayout.objects.filter(user=user)
    return {
        'layout':
        layout,
        'is_favourite':
        not favourite_layout or not layout in favourite_layout[0].layout.all(),
        'view':
        view,
        'MEDIA_URL':
        settings.MEDIA_URL,
    }


register.inclusion_tag("favourite.html", takes_context=True)(favourite)
コード例 #4
0
ファイル: fobi_tags.py プロジェクト: vlasebian/django-fobi
            auth_url = settings.LOGIN_URL
            auth_icon_class = 'icon-signin'
            auth_link_text = _('Log in')
        except Exception:
            auth_url = ''
            auth_icon_class = ''
            auth_link_text = ''

    return {
        'auth_link': auth_url,
        'auth_icon_class': auth_icon_class,
        'auth_link_text': auth_link_text
    }


register.inclusion_tag('fobi/snippets/render_auth_link.html',
                       takes_context=True)(render_auth_link)


@register.inclusion_tag(THEME.forms_list_template, takes_context=True)
def render_fobi_forms_list(context, queryset, *args, **kwargs):
    """Render the list of fobi forms.

    :syntax:

        {% render_fobi_forms_list [queryset] [show_edit_link] \
                                             [show_delete_link] \
                                             [show_export_link] %}

    :example:

        {% render_fobi_forms_list queryset show_edit_link=True \
コード例 #5
0
ファイル: admin_list.py プロジェクト: johnnypenn/advisoryscan
                page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
                page_range.append(DOT)
                page_range.extend(range(paginator.pages - ON_ENDS, paginator.pages))
            else:
                page_range.extend(range(page_num + 1, paginator.pages))

    need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
    return {
        'cl': cl,
        'pagination_required': pagination_required,
        'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
        'page_range': page_range,
        'ALL_VAR': ALL_VAR,
        '1': 1,
    }
pagination = register.inclusion_tag('admin/pagination.html')(pagination)

def result_headers(cl):
    lookup_opts = cl.lookup_opts

    for i, field_name in enumerate(lookup_opts.admin.list_display):
        try:
            f = lookup_opts.get_field(field_name)
            admin_order_field = None
        except models.FieldDoesNotExist:
            # For non-field list_display values, check for the function
            # attribute "short_description". If that doesn't exist, fall
            # back to the method name. And __str__ is a special-case.
            if field_name == '__str__':
                header = lookup_opts.verbose_name
            else:
コード例 #6
0
from django.contrib.admin.templatetags.admin_list import items_for_result, result_headers
from django.core.urlresolvers import reverse
from django.template import Library
from django.utils.safestring import mark_safe


register = Library()

def project_result_list(cl):
    headers = list(result_headers(cl))
    headers.append({'text': mark_safe('&nbsp;')})

    results = list()

    for project in cl.result_list:
        rl = list(items_for_result(cl,project,None))

        url = reverse('admin_project_sendcredentials', args=[project.projectname])
        content = mark_safe('<td><a href="%s">Send Credentials</a></td>' % url)

        rl.append(content)
        results.append(rl)

    return {
        'cl': cl,
        'result_headers': headers,
        'results': results
    }
project_result_list = register.inclusion_tag("admin/change_list_results.html")(project_result_list)
コード例 #7
0
            else:
                page_range.extend(range(page_num + 1, paginator.pages))

    need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
    return {
        'cl': cl,
        'pagination_required': pagination_required,
        'show_all_url': need_show_all_link
        and cl.get_query_string({ALL_VAR: ''}),
        'page_range': page_range,
        'ALL_VAR': ALL_VAR,
        '1': 1,
    }


pagination = register.inclusion_tag('admin/pagination.html')(pagination)


def result_headers(cl):
    lookup_opts = cl.lookup_opts

    for i, field_name in enumerate(lookup_opts.admin.list_display):
        try:
            f = lookup_opts.get_field(field_name)
        except models.FieldDoesNotExist:
            # For non-field list_display values, check for the function
            # attribute "short_description". If that doesn't exist, fall
            # back to the method name. And __str__ is a special-case.
            if field_name == '__str__':
                header = lookup_opts.verbose_name
            else:
コード例 #8
0
from django.template import Library, Node

register = Library()

def field_errors(field):
    return {'errors': field.errors}

register.inclusion_tag('domes/templatetags/field_errors.html')(field_errors)

def form_errors(form):

    has_field_errors = False
    
    #Any field errors?
    for field in form:
        if field.errors:
            has_field_errors = True
            break
    
    return {'has_field_errors': has_field_errors, 'form': form}

register.inclusion_tag('domes/templatetags/form_errors.html')(form_errors)
コード例 #9
0
def row_count(row, page):
    return row + (page.number - 1) * page.paginator.per_page


register.filter('row_count', row_count)


def table_header(context, headers=None):
    # add things for the header here
    if headers:
        context["headers"] = headers
    return context


register.inclusion_tag('table_header.html', takes_context=True)(table_header)


def paginator(context, adjacent_pages=2):
    """
    To be used in conjunction with the object_list generic view.

    Adds pagination context variables for use in displaying first, adjacent and
    last page links in addition to those created by the object_list generic
    view.

    """
    results_this_page = context["page"].object_list.count()
    context.update({
        'results_this_page': results_this_page,
    })
コード例 #10
0
    new_context['record_url'] = context['doc']['record_url']
    try:
        full_title = context['doc']['full_title']
    except KeyError:
        full_title = _('Untitled')
    try:
        short_title = context['doc']['title']
    except KeyError:
        short_title = full_title
    new_context['short_title'] = short_title
    rest_of_title = full_title.replace(short_title, '', 1)
    new_context['rest_of_title'] = rest_of_title
    return new_context


register.inclusion_tag('discovery/snippets/result_title.html',
                       takes_context=True)(title_link)


def add_sort(context, sort_type):
    params = []
    query = context['query']
    if query:
        params.append(('q', query.encode('utf8')))
    limits_param = context['limits_param']
    if limits_param:
        params.append(('limits', limits_param.encode('utf8')))
    params.append(('sort', sort_type.encode('utf8')))
    return {'urlparams': urllib.urlencode(params)}


register.inclusion_tag('discovery/snippets/search_url.html',
コード例 #11
0
        'size_x'        : size[0],
        'size_y'        : size[1],
        'placehold_size': "%sx%s" % (placehold_size[0], placehold_size[1]),
        'real'          : alias in ('real', 'real_inverted'),
        'url'           : url,
        'show_tooltip'  : show_tooltip,
        'request'       : request,
        'caption_cache_key': "%d_%s_%s_%s" % (
            image.id, revision, alias, request.LANGUAGE_CODE if hasattr(request, "LANGUAGE_CODE") else "en"),
        'badges'        : badges,
        'animated'      : animated,
        'get_thumb_url' : get_thumb_url,
        'thumb_url'     : thumb_url,
        'link'          : link,
        'nav_ctx'       : nav_ctx,
        'nav_ctx_extra': nav_ctx_extra,
    }.items())
register.inclusion_tag(
    'astrobin_apps_images/snippets/image.html',
    takes_context = True)(astrobin_image)


@register.simple_tag(takes_context = True)
def random_id(context, size = 8, chars = string.ascii_uppercase + string.digits):
    id = ''.join(random.choice(chars) for x in range(size))
    context['randomid'] = id
    return ''



コード例 #12
0
ファイル: admin_totals.py プロジェクト: isasiluis28/superbar
from django.template import Library

register = Library()


def totals_row(cl):
    total_functions = getattr(cl.model_admin, 'total_functions', {})
    totals = []
    for field_name in cl.list_display:
        if field_name in total_functions:
            values = [getattr(i, field_name) for i in cl.result_list]
            totals.append(total_functions[field_name](values))
        else:
            totals.append('')
    return {'cl': cl, 'totals_row': totals}


totals_row = register.inclusion_tag("admin/facturas/totals_row.html")(totals_row)
コード例 #13
0
ファイル: messagebox.py プロジェクト: Alotor/intranet
from django.template import Library
from django.utils.translation import ugettext as _

from cmsutils.log import get_and_delete_messages, send_error

register = Library()


def messagebox(context):
    """ Render message box """
    request = context['request']
    portal_messages = context['messages']
    if not portal_messages:
        portal_messages = get_and_delete_messages(request)
    if not portal_messages:
        if 'form' in context:
            form = context['form']
            if getattr(form, 'errors', []):
                if form.non_field_errors():
                    send_error(request, form.non_field_errors())
                send_error(request, _('Form filled has errors. Please correct'))
                portal_messages = get_and_delete_messages(request)
    return { 'portal_messages':  portal_messages }
messagebox = register.inclusion_tag('cmsutils/messagebox.html',
                                   takes_context=True)(messagebox)
コード例 #14
0
    all_letters = list(_get_default_letters(cl.model_admin) | letters_used)
    all_letters.sort()
    
    choices = [{
        'link': link({alpha_field: letter}), 
        'title': letter,
        'active': letter == alpha_lookup,
        'has_entries': letter in letters_used,} for letter in all_letters]
    all_letters = [{
        'link': cl.get_query_string(None, [alpha_field]),
        'title': _('All'),
        'active': '' == alpha_lookup,
        'has_entries': True
    },]
    return {'choices': all_letters + choices}
alphabet = register.inclusion_tag('admin/alphabet.html')(alphabet)

class AlphabetFilterNode(Node):
    """
    Provide a list of links for first characters on items in a queryset
    
    {% qs_alphabet_filter objects "lastname" "myapp/template.html" %}
    """
    def __init__(self, qset, field_name, filtered=None,
        template_name="alphafilter/alphabet.html"):
        self.qset = Variable(qset)
        self.field_name = Variable(field_name)
        self.template_name = Variable(template_name)
        self.filtered = filtered
    
    def render(self, context):
コード例 #15
0
ファイル: posttags.py プロジェクト: godric01/django-blog
from django.utils.dateformat import format
from blog.templatetags.themes import theme_template_url

register = Library()
def get_tagged_posts(tags,number_of_posts,exclude_id = None):
    '''get tagged related posts'''
    posts = []
    for tag in tags:
        if len(posts) < number_of_posts:
            for p in tag.post_set.filter(post_type__iexact='post')[:number_of_posts-len(posts)]:
                if (not exclude_id or p.id != exclude_id) and p not in posts:
                    posts.append(p)
        else:
            break
    return {'posts':posts}
register.inclusion_tag('blog/tags/related_posts.html')(get_tagged_posts)

class archive:
    link = ''
    title = ''

def get_archivelist(context):
    '''
    get the month list which have posts
    '''
    months = Post.objects.dates('pubdate','month',order='DESC')
    archive_months = []
    for mon in months:
        m = archive()
        m.link = "/" + format(mon,'Y/m') + "/"
        m.title = format(mon,'b,Y')
コード例 #16
0
        'unsaved_changes':
        inplace_settings.INPLACEEDIT_UNSAVED_TEXT,
        'inplace_get_field_url':
        inplace_settings.INPLACE_GET_FIELD_URL or reverse('inplace_get_field'),
        'inplace_save_url':
        inplace_settings.INPLACE_SAVE_URL or reverse('inplace_save'),
        'field_types':
        inplace_settings.INPLACE_FIELD_TYPES,
        'focus_when_editing':
        json.dumps(inplace_settings.INPLACE_FOCUS_WHEN_EDITING),
        'inplace_js_extra':
        getattr(request, 'inplace_js_extra', '')
    }


register.inclusion_tag("inplaceeditform/inplace_js.html",
                       takes_context=True)(inplace_js)


def inplace_css(context, toolbar=False):
    request = context['request']
    request.inplace_css_rendered = True
    return {
        'STATIC_URL': get_static_url(),
        'ADMIN_MEDIA_PREFIX': get_admin_static_url(),
        'toolbar': toolbar,
        'inplace_js_extra': getattr(request, 'inplace_css_extra', '')
    }


register.inclusion_tag("inplaceeditform/inplace_css.html",
                       takes_context=True)(inplace_css)
コード例 #17
0
ファイル: navigation.py プロジェクト: Lars/django-inventory
    except TypeError:
        return name


class GetNavigationLinks(Node):
    def __init__(self, *args):
        self.menu_name = None
        if args:
            self.menu_name = args[0]

    def render(self, context):
        menu_name = resolve_template_variable(context, self.menu_name)
        context['object_navigation_links'] = _get_object_navigation_links(context, menu_name)
        return ''


@register.tag
def get_object_navigation_links(parser, token):
    args = token.split_contents()
    return GetNavigationLinks(*args[1:])


def object_navigation_template(context):
    return {
        'horizontal':True,
        'object_navigation_links':_get_object_navigation_links(context)
    }
    return new_context
register.inclusion_tag('generic_navigation.html', takes_context=True)(object_navigation_template)

コード例 #18
0
ファイル: satchmo_google.py プロジェクト: eyeyunianto/satchmo
from django.template import Library, RequestContext
from django.conf import settings
from satchmo_store.contact.models import Contact
from livesettings.functions import config_value
import sys

register = Library()

def show_tracker(context, secure=False):
    """
    Output the google tracker code.
    """
    return ({"GOOGLE_CODE": config_value('GOOGLE', 'ANALYTICS_CODE'), "secure" : secure})

register.inclusion_tag("shop/google-analytics/tracker.html", takes_context=True)(show_tracker)

def show_receipt(context):
    """
    Output our receipt in the format that Google Analytics needs.
    """
    return({'Store': settings.SITE_NAME,
            'order': context['order']})

register.inclusion_tag("shop/google-analytics/receipt.html", takes_context=True)(show_receipt)

def google_track_signup(context):
    """
    Output a a new user signup in the format that Google Analytics needs.
    """
    request = context['request']
    try:
コード例 #19
0
ファイル: silk_inclusion.py プロジェクト: yuekui/django-silk

def profile_menu(request, profile, silk_request=None):
    context = {'request': request, 'profile': profile}
    if silk_request:
        context['silk_request'] = silk_request
    return context


def profile_summary(profile):
    return {'profile': profile}


def heading(text):
    return {'text': text}


def code(lines, actual_line):
    return {'code': lines, 'actual_line': [x.strip() for x in actual_line]}


register.inclusion_tag('silk/inclusion/request_summary.html')(request_summary)
register.inclusion_tag('silk/inclusion/request_summary_row.html')(
    request_summary_row)
register.inclusion_tag('silk/inclusion/profile_summary.html')(profile_summary)
register.inclusion_tag('silk/inclusion/code.html')(code)
register.inclusion_tag('silk/inclusion/request_menu.html')(request_menu)
register.inclusion_tag('silk/inclusion/profile_menu.html')(profile_menu)
register.inclusion_tag('silk/inclusion/root_menu.html')(root_menu)
register.inclusion_tag('silk/inclusion/heading.html')(heading)
コード例 #20
0
ファイル: user.py プロジェクト: manolisn/Farm-Subsidy
from django.template import Library, Node

register = Library()

def user_menu(user):
  return {'user' : user}


register.inclusion_tag('blocks/user_menu.html')(user_menu)
コード例 #21
0
        qe_form = False
    if cl.formset:
        if qe_form:
            for res, form in zip(cl.result_list, cl.formset.forms):
                yield {'fields':list(items_for_result(cl, res, form)), 
                'quickedit':form}
                #'quickedit':form(instance=res)}
        else:
            for res, form in zip(cl.result_list, cl.formset.forms):
                yield list(items_for_result(cl, res, form))
    else:
        if qe_form:
            for res in cl.result_list:
                yield {'fields':list(items_for_result(cl, res, None)), 
                'quickedit':form}
                #'quickedit':form(instance=res)}
        else:
            for res in cl.result_list:
                yield list(items_for_result(cl, res, None))

def qe_result_list(context, cl):
    if context.has_key('STATIC_URL'):
        static_url = 'STATIC_URL'
    else:
        static_url = 'MEDIA_URL'
    return {'cl': cl,
            'result_headers': list(result_headers(cl)),
            'results': list(results(cl)),
            'STATIC_URL': context[static_url]}
qe_result_list = register.inclusion_tag("admin/qe_change_list_results.html", takes_context=True)(qe_result_list)
コード例 #22
0
    parameter:

    form
        form variable

    Usage::

        {% form_ext form %}
    
    the current implementation is equivalent to::

        {% include "goflow/apptools/edit_form.html" %}
    '''
    return {'form':form}
form_ext = register.inclusion_tag("goflow/apptools/edit_form.html")(form_ext)

def _get_transitions_out_images(activity):
    if activity.split_mode == 'and':
        raise Exception('_get_transitions_out_images: xor split_mode required')
    transitions = Transition.objects.filter(input=activity)
    icons = []
    for t in transitions:
        if t.icon: icons.append(t.icon)


def input_buttons(context):
    '''
    This will insert submit buttons in application templates.

    The template *goflow/apptools/input_buttons.html* is used for rendering.
コード例 #23
0
ファイル: mptt_admin.py プロジェクト: shultais/django-mptt
    if form and not form[cl.model._meta.pk.name].is_hidden:
        yield mark_safe('<td>%s</td>' % force_text(form[cl.model._meta.pk.name]))


def mptt_results(cl):
    if cl.formset:
        for res, form in zip(cl.result_list, cl.formset.forms):
            yield list(mptt_items_for_result(cl, res, form))
    else:
        for res in cl.result_list:
            yield list(mptt_items_for_result(cl, res, None))


def mptt_result_list(cl):
    """
    Displays the headers and data list together
    """
    return {'cl': cl,
            'result_hidden_fields': list(result_hidden_fields(cl)),
            'result_headers': list(result_headers(cl)),
            'results': list(mptt_results(cl))}

# custom template is merely so we can strip out sortable-ness from the column headers
# Based on admin/change_list_results.html (1.3.1)
if IS_GRAPPELLI_INSTALLED:
    mptt_result_list = register.inclusion_tag(
        "admin/grappelli_mptt_change_list_results.html")(mptt_result_list)
else:
    mptt_result_list = register.inclusion_tag(
        "admin/mptt_change_list_results.html")(mptt_result_list)
コード例 #24
0
from django.template import Library
from blog.util.code_hilite import to_html

register = Library()

register.filter("to_html", to_html)

def show_post_brief(context, post):
    return {
        "post": post,
        "last": context["forloop"]["last"],
        "can_edit": context["user"].is_staff,
    }
register.inclusion_tag("blog/post_brief.html", takes_context=True)(show_post_brief)

@register.filter
def date_microformat(d):
    '''
        Microformat version of a date.
        2009-02-10T02:58:00+00:00 (ideal)
        2009-02-09T17:54:41.181868-08:00 (mine)
    '''
    return d.isoformat()
コード例 #25
0
# coding: utf-8
from django.template import Library

register = Library()


def custom_admin_list_filter(cl, spec):
    return {
        'title': spec.title if not callable(spec.title) else spec.title(),
        'choices': list(spec.choices(cl))
    }


custom_admin_list_filter = register.inclusion_tag('admin/custom_filter.html')(
    custom_admin_list_filter)
コード例 #26
0
ファイル: blog_tags.py プロジェクト: digideskio/homepage-1
        html = rst_to_html(obj.content)
    else:
        html = obj.content

    return mark_safe(html)
register.filter("to_html", to_html)


def show_post_brief(context, post):
    return {
        "post": post,
        "last": context["forloop"]["last"],
        "can_edit": context["user"].is_staff,
    }

register.inclusion_tag("blog/post_brief.html",
                       takes_context=True)(show_post_brief)


@register.filter
def date_microformat(d):
    '''
        Microformat version of a date.
        2009-02-10T02:58:00+00:00 (ideal)
        2009-02-09T17:54:41.181868-08:00 (mine)
    '''
    return d.isoformat()

STRIKE_REPL_RE = re.compile("< *strike *>[^<]*</ *strike *>", re.IGNORECASE)


def html_to_text(html):
コード例 #27
0
ファイル: fobi_tags.py プロジェクト: garmoncheg/django-fobi
            auth_icon_class = ""
            auth_link_text = ""
    else:
        try:
            auth_url = settings.LOGIN_URL
            auth_icon_class = "icon-signin"
            auth_link_text = _("Log in")
        except Exception as e:
            auth_url = ""
            auth_icon_class = ""
            auth_link_text = ""

    return {"auth_link": auth_url, "auth_icon_class": auth_icon_class, "auth_link_text": auth_link_text}


register.inclusion_tag("fobi/snippets/render_auth_link.html", takes_context=True)(render_auth_link)

# *****************************************************************************
# *****************************************************************************
# *****************************************************************************
# **************************** Permission tags ********************************
# *****************************************************************************
# *****************************************************************************
# *****************************************************************************


class HasEditFormEntryPermissionsNode(Node):
    """
    Node for ``has_edit_form_entry_permissions`` tag.
    """
コード例 #28
0
ファイル: award_table.py プロジェクト: bchruszc/Wiz
from django.template import Library

register = Library()

def award_table(award):
    return {'award':award}

register.inclusion_tag('scoreboard/award_table.html')(award_table)
コード例 #29
0
ファイル: posttags.py プロジェクト: feitianyiren/ddtcms
from django.utils.dateformat import format
from blog.templatetags.themes import theme_template_url

register = Library()
def get_tagged_posts(tags,number_of_posts,exclude_id = None):
    '''get tagged related posts'''
    posts = []
    for tag in tags:        
        if len(posts) < number_of_posts:
            for p in tag.post_set.filter(post_type__iexact='post')[:number_of_posts-len(posts)]:
                if (not exclude_id or p.id != exclude_id) and p not in posts:
                    posts.append(p)                   
        else:
            break    
    return {'posts':posts}
register.inclusion_tag(['%s/blog/tags/related_posts.html' % theme_template_url(),
                        'blog/tags/related_posts.html'])(get_tagged_posts)

class archive:
    link = ''
    title = ''
    
def get_archivelist(context):
    '''
    get the month list which have posts
    ''' 
    months = Post.objects.dates('pubdate','month',order='DESC')
    archive_months = []    
    for mon in months:
        m = archive()
        m.link = "/" + format(mon,'Y/m') + "/"
        m.title = format(mon,'b,Y')
コード例 #30
0
            page_numbers.append(None)

        for i in range(page_obj.number - before_after_amount, page_obj.number):
            page_numbers.append(i)

    else:
        for i in range(1, page_obj.number):
            page_numbers.append(i)

    # Current page and pages after current page
    if page_obj.number + first_last_amount + before_after_amount < paginator.num_pages:
        for i in range(page_obj.number, page_obj.number + before_after_amount + 1):
            page_numbers.append(i)

        page_numbers.append(None)

        for i in range(paginator.num_pages - first_last_amount + 1, paginator.num_pages + 1):
            page_numbers.append(i)

    else:
        for i in range(page_obj.number, paginator.num_pages + 1):
            page_numbers.append(i)

    return {
        'paginator': paginator,
        'page_obj': page_obj,
        'page_numbers': page_numbers
    }

register.inclusion_tag('pagination.html', takes_context=True)(render_paginator)
コード例 #31
0
    """
    if cl.formset:
        for res, form in zip(cl.result_list, cl.formset.forms):
            patch_document(serializable_value, res)
            yield ResultList(form, items_for_result(cl, res, form))
    else:
        for res in cl.result_list:
            patch_document(serializable_value, res)
            res._meta = res._admin_opts
            yield ResultList(None, items_for_result(cl, res, None))

def document_result_list(cl):
    """
    Displays the headers and data list together
    """
    headers = list(result_headers(cl))
    try:
        num_sorted_fields = 0
        for h in headers:
            if h['sortable'] and h['sorted']:
                num_sorted_fields += 1
    except KeyError:
        pass

    return {'cl': cl,
            'result_hidden_fields': list(result_hidden_fields(cl)),
            'result_headers': headers,
            'num_sorted_fields': num_sorted_fields,
            'results': list(results(cl))}
result_list = register.inclusion_tag("admin/change_list_results.html")(document_result_list)
コード例 #32
0
from django.template import Library

register = Library()

def field_errors(field):
    return {'errors': field.errors}

register.inclusion_tag('frontend/templatetags/field_errors.html')(field_errors)

def form_errors(form):

    has_field_errors = False
    
    #Any field errors?
    for field in form:
        if field.errors:
            has_field_errors = True
            break
    
    return {'has_field_errors': has_field_errors, 'form': form}

register.inclusion_tag('frontend/templatetags/form_errors.html')(form_errors)
コード例 #33
0
        for res in cl.result_list:
            patch_document(serializable_value, res)
            yield ResultList(None, items_for_result(cl, res, None))


def document_result_list(cl):
    """
    Displays the headers and data list together
    """
    headers = list(result_headers(cl))
    try:
        num_sorted_fields = 0
        for h in headers:
            if h["sortable"] and h["sorted"]:
                num_sorted_fields += 1
    except KeyError:
        pass

    return {
        "cl": cl,
        "result_hidden_fields": list(result_hidden_fields(cl)),
        "result_headers": headers,
        "num_sorted_fields": num_sorted_fields,
        "results": list(results(cl)),
    }


result_list = register.inclusion_tag("admin/change_list_results.html")(
    document_result_list
)
コード例 #34
0
        'title': letter,
        'active': letter == alpha_lookup,
        'has_entries': letter in letters_used,
    } for letter in all_letters]
    all_letters = [
        {
            'link': cl.get_query_string(None, [alpha_field]),
            'title': _('All'),
            'active': '' == alpha_lookup,
            'has_entries': True
        },
    ]
    return {'choices': all_letters + choices}


alphabet = register.inclusion_tag('admin/alphabet.html')(alphabet)


class AlphabetFilterNode(Node):
    """
    Provide a list of links for first characters on items in a queryset

    {% qs_alphabet_filter objects "lastname" "myapp/template.html" %}
    """
    def __init__(self,
                 qset,
                 field_name,
                 filtered=None,
                 template_name="alphafilter/alphabet.html",
                 strip_params=None):
        self.qset = Variable(qset)
コード例 #35
0
ファイル: award_table.py プロジェクト: bchruszc/Wiz
from django.template import Library

register = Library()


def award_table(award):
    return {'award': award}


register.inclusion_tag('scoreboard/award_table.html')(award_table)
コード例 #36
0
ファイル: proto_tags.py プロジェクト: ansp-2015/arquea
            'nome': u'administrativos',
            'rel': administrativos
        })
    if len(tecnicos) > 0:
        retorno['relatorios'].append({'nome': u'técnicos', 'rel': tecnicos})
    if len(verificacoes) > 0:
        retorno['relatorios'].append({
            'nome': u'de verificações (Acesso restrito)',
            'rel': verificacoes
        })

    return retorno


# Register the custom tag as an inclusion tag with takes_context=True.
register.inclusion_tag('admin/relatorios.html',
                       takes_context=True)(lista_relatorios)


@register.filter(name='moeda_css')
def moeda_css(value, nac=1):
    """
    Novo metodo para formatar o valor em moeda, com valor negativo em cor vermelha em css
    """
    return mark_safe(moeda(value, nac, False, True))


@register.filter(name='moeda_valor')
def moeda_valor(value, nac=1):
    """
    Novo metodo para formatar o valor em moeda, mas remover o prefixo da moeda (ex: R$)
    """
コード例 #37
0
register = Library()

assignment_tag = getattr(register, 'assignment_tag', register.simple_tag)


def filer_actions(context):
    """
    Track the number of times the action field has been rendered on the page,
    so we know which value to use.
    """
    context['action_index'] = context.get('action_index', -1) + 1
    return context


filer_actions = register.inclusion_tag("admin/filer/actions.html",
                                       takes_context=True)(filer_actions)


@register.simple_tag(takes_context=True)
def filer_admin_context_url_params(context, first_separator='?'):
    return admin_url_params_encoded(context['request'],
                                    first_separator=first_separator)


@register.simple_tag(takes_context=True)
def filer_admin_context_hidden_formfields(context):
    request = context.get('request')
    return format_html_join(
        '\n',
        '<input type="hidden" name="{0}" value="{1}">',
        admin_url_params(request).items(),
コード例 #38
0
from django.template import Node, NodeList
from django.template import TemplateSyntaxError
from django.template import Library
from product.models import Product
from livesettings.functions import config_value

register = Library()


def recentlyviewed(recent, slug=""):
    """Build a list of recent products, skipping the current one if given."""
    if slug:
        recent = [r for r in recent if slug != r.slug]

    rmax = config_value('PRODUCT', 'RECENT_MAX')
    if len(recent) > rmax:
        recent = recent[:rmax]
    return {
        'recent_products': recent,
    }


register.inclusion_tag('recentlist/_recently_viewed.html',
                       takes_context=False)(recentlyviewed)
コード例 #39
0
                    # We've processed the next item now too.
                    i += 1
            if sublist_item:
                sublist = _helper(sublist_item, tabs+1)
                sublist = '\n%s<ul>\n%s\n%s</ul>\n%s' % (indent, sublist,
                                                         indent, indent)
            hyperlink = "<a href='%s'>%s</a>" % (title.get_absolute_url(),
                                                 title.name)
            output.append('%s<li>%s%s</li>' % (indent,
                    escaper(force_unicode(hyperlink)), sublist))
            i += 1
        return '\n'.join(output)
    value, converted = convert_old_style_list(value)
    return mark_safe(_helper(value))
org_outline.is_safe = True
org_outline.needs_autoescape = True

register.filter(org_outline)

def show_task(task):
    return {"task": task}
register.inclusion_tag("orgs/task_item.html")(show_task)

def show_aim(aim):
    return {"aim": aim}
register.inclusion_tag("orgs/aim_item.html")(show_aim)

def show_meeting_topic(topic):
    return {"topic": topic}
register.inclusion_tag("orgs/topic_item.html")(show_meeting_topic)
コード例 #40
0
ファイル: flatpage_tags.py プロジェクト: justquick/fodcl
from django.template import Library
from django.contrib.flatpages.models import FlatPage

register = Library()

def get_pages():
    return {'pages':FlatPage.objects.order_by('-pk')[:5]}
    
register.inclusion_tag('pagelist.html')(get_pages)
コード例 #41
0
    brands_group = dict(heading='Brands', rows=[], cols=cols)
    brands_list = Brand.objects.filter(id__in =
            Product.objects.filter(
                category__in = cat_list,status='active').distinct(
                    'brand').values('brand'))[:limit]
    split_and_add(brands_list, cols, brands_group)
    groups.append(brands_group)
    return groups

def render_mobile_menu_clearance(request):
    menu_context = {}
    menu_context['clearance_sale']=get_clearance_tags(request)
    menu_context['request'] = request
    return menu_context
register.inclusion_tag('web/clearance_list.html')(render_mobile_menu_clearance)

def render_mobile_menu_category(request):
    menu_key = 'menu#%s' % (request.client.client.id)
    menu_context = cache.get(menu_key)
    if not menu_context:
        menu_context = get_menu(request)
        cache.set(menu_key, menu_context, 3600)
    menu_context['request'] = request
    return menu_context
register.inclusion_tag('web/category_list.html')(render_mobile_menu_category)

def render_daily_deal(request):
    daily_deal_context = {}
    _client = request.client.client
    steal_of_the_day = DailyDeal.objects.filter(type='hero_deal', starts_on__lte = datetime.now(), ends_on__gte = datetime.now(), client=_client)
コード例 #42
0
ファイル: links.py プロジェクト: woshicainiao/ddtcms
#coding=utf-8
from django.template import Library

from blog.models import Links
from blog.templatetags.themes import theme_template_url

register = Library()
def get_links(context):  
    links = Links.objects.all()
    return {'links':links}   
register.inclusion_tag(['%s/blog/tags/links.html' % theme_template_url(),
                        'blog/tags/links.html'],
                        takes_context=True)(get_links)
コード例 #43
0
ファイル: tags.py プロジェクト: pierfra-r/astrobin
        view = context['view']
    if view is None:
        view = context['request'].GET.get('view', 'default')

    return {
        'image_list': object_list,
        'request': context['request'],
        'paginate_by': paginate_by,
        'alias': alias,
        'view': view,
        'nav_ctx': nav_ctx,
        'nav_ctx_extra': nav_ctx_extra,
    }


register.inclusion_tag('inclusion_tags/image_list.html', takes_context=True)(image_list)


@register.inclusion_tag('inclusion_tags/search_image_list.html', takes_context=True)
def search_image_list(context, paginate=True, **kwargs):
    request = context['request']
    q = request.GET.get('q')
    telescope = request.GET.get('telescope')
    camera = request.GET.get('camera')
    country = get_client_country_code(request)
    equipment_brand_listings = None

    if telescope or camera or q:
        equipment_brand_listings = EquipmentBrandListing.objects \
            .annotate(distance=TrigramDistance('brand__name', telescope or camera or q)) \
            .filter(distance__lte=.85, retailer__countries__icontains=country)
コード例 #44
0
            yield mark_safe(u'<td%s%s>%s</td>' %
                            (row_class, padding_attr, result_repr))
    if form:
        yield mark_safe(u'<td>%s</td>' %
                        force_unicode(form[cl.model._meta.pk.name]))


def mptt_results(cl):
    if cl.formset:
        for res, form in zip(cl.result_list, cl.formset.forms):
            yield list(mptt_items_for_result(cl, res, form))
    else:
        for res in cl.result_list:
            yield list(mptt_items_for_result(cl, res, None))


def mptt_result_list(cl):
    """
    Displays the headers and data list together
    """
    return {
        'cl': cl,
        'result_headers': list(result_headers(cl)),
        'results': list(mptt_results(cl))
    }


# custom template is merely so we can strip out sortable-ness from the column headers
mptt_result_list = register.inclusion_tag(
    "admin/mptt_change_list_results.html")(mptt_result_list)
コード例 #45
0
        'revision_title': image_revision.title if hasattr(image_revision, 'label') else None,
        'w': w,
        'h': h,
        'instant': instant,
        'fancybox': fancybox,
        'fancybox_url': reverse('image_rawthumb', kwargs={
            'id': image.get_id(),
            'alias': 'hd',
            'r': revision_label,
        }) + '?sync',
        'rel': rel,
    }.items()))


register.inclusion_tag(
    'astrobin_apps_images/snippets/image.html',
    takes_context=True)(astrobin_image)


@register.simple_tag(takes_context=True)
def random_id(context, size=8, chars=string.ascii_uppercase + string.digits):
    id = ''.join(random.choice(chars) for x in range(size))
    context['randomid'] = id
    return ''


@register.simple_tag(takes_context=True)
def cache_image_list(context):
    # Don't cache for gallery owner.
    if context['requested_user'] and context['request'].user == context['requested_user']:
        return False
コード例 #46
0
ファイル: posts.py プロジェクト: abe33/Abe-Python-Lib
			try :
				c = get_definition_with_path(d)
				if c is not None :
					d = c
			except:
				pass
			
			res = r.search( path )
			if res is not None :
				if callable(d):
					desc = d(res)
				else:
					desc = d
	
	return '<meta name="description" content="%s"/>' % desc

render_post = register.inclusion_tag("posts/post_view.html")(render_post)
render_post_with_id = register.inclusion_tag("posts/post_view.html")(render_post_with_id)
render_orphan = register.inclusion_tag("posts/orphan_view.html")(render_orphan)

register.simple_tag( get_gravatar_md5 )
register.simple_tag( render_categories_list )
register.simple_tag( get_page_description_meta )
register.tag( get_post )
register.tag( get_post_by_comment_id )
register.tag( get_post_category_list )
register.tag( get_post_archives_list )
register.tag( get_comment_archives_list )
register.tag( get_post_tags_list )
register.tag( get_site_links_list )
コード例 #47
0
ファイル: admin_media.py プロジェクト: joaquinquintas/trade
def image_sorter(context, model):
    """
    Adds a sortable list of images for models with a RelatedImagesField
    """
    form = AddRelatedImageForm(initial={
        'id': model.id,
        'model': "%s.%s" % (model._meta.app_label, model._meta.object_name),
    })

    context.update({
        'model' : model,
        'form' : form,
        'meta': model._meta
    })
    return context
register.inclusion_tag("admin/media/includes/image_sort.html", takes_context=True)(image_sorter)

def file_sorter(context, model):
    """
    Adds a sortable list of files for models with a RelatedFilesField
    """
    form = AddRelatedFileForm(initial={
        'id':model.id,
        'model': "%s.%s" % (model._meta.app_label, model._meta.object_name),
    })

    context.update({
        'model' : model,
        'form' : form,
        'meta': model._meta
    })
コード例 #48
0
from django.template import Library
from rt_www.admin.templatetags.admin_list import result_list, pagination

register = Library()

pagination = register.inclusion_tag('admin/pagination.html')(pagination)
result_list = register.inclusion_tag('admin/change_list_results.html')(
    result_list)
コード例 #49
0
            else:
                page_range.extend(range(page_num + 1, paginator.num_pages))

    need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
    return {
        'cl': cl,
        'pagination_required': pagination_required,
        'show_all_url': need_show_all_link
        and cl.get_query_string({ALL_VAR: ''}),
        'page_range': page_range,
        'ALL_VAR': ALL_VAR,
        '1': 1,
    }


pagination = register.inclusion_tag('admin/pagination.html')(pagination)


def result_headers(cl):
    """
    Generates the list column headers.
    """
    lookup_opts = cl.lookup_opts

    for i, field_name in enumerate(cl.list_display):
        header, attr = label_for_field(field_name,
                                       cl.model,
                                       model_admin=cl.model_admin,
                                       return_attr=True)
        if attr:
            # if the field is the action checkbox: no sorting and special class
コード例 #50
0
from django.template import Library, Node, Variable, VariableDoesNotExist
from django.utils.translation import ugettext as _

register = Library()


def filter_form(context):
    new_context = context

    new_context.update({
        'form':context['filter_form'],
        'submit_method':'get',
        'title':_(u'Filter'),
    })
    return new_context
register.inclusion_tag('generic_form_subtemplate.html', takes_context=True)(filter_form)
コード例 #51
0

def submit_row_inline(context):
    opts = context['opts']
    change = context['change']
    is_popup = context['is_popup']
    save_as = context['save_as']
    return {
        'onclick_attrib': (opts.get_ordered_objects() and change
                           and 'onclick="submitOrderForm();"' or ''),
        'show_delete_link': (not is_popup and context['has_delete_permission']
                             and (change or context['show_delete'])),
        'show_save_as_new':
        not is_popup and change and save_as,
        'show_save_and_add_another':
        context['has_add_permission'] and not is_popup
        and (not save_as or context['add']),
        'show_save_and_continue':
        not is_popup and context['has_change_permission'],
        'is_popup':
        is_popup,
        'show_save':
        True
    }


# As you can see, we really want the first template dir. UPDATE: Templates MUST be in the project, not in EMMA.
submit_row_inline = register.inclusion_tag(
    os.path.join(settings.TEMPLATE_DIRS[0],
                 'admin/interface/metadata/submit_line.html'),
    takes_context=True)(submit_row_inline)
コード例 #52
0
from __future__ import print_function
from django.template import Library
from django.conf import settings
from satchmo_store.contact.models import Contact
from livesettings.functions import config_value
import sys

register = Library()

def show_tracker(context, secure=False):
    """
    Output the google tracker code.
    """
    return ({"GOOGLE_CODE": config_value('GOOGLE', 'ANALYTICS_CODE'), "secure" : secure})

register.inclusion_tag("shop/google-analytics/tracker.html", takes_context=True)(show_tracker)

def show_receipt(context):
    """
    Output our receipt in the format that Google Analytics needs.
    """
    return({'Store': settings.SITE_NAME,
            'order': context['order']})

register.inclusion_tag("shop/google-analytics/receipt.html", takes_context=True)(show_receipt)

def google_track_signup(context):
    """
    Output a a new user signup in the format that Google Analytics needs.
    """
    request = context['request']
コード例 #53
0
            else:
                result_repr = conditional_escape(result_repr)
            yield mark_safe(u'%s' % (result_repr))
    if form:
        yield mark_safe(force_unicode(form[cl.model._meta.pk.name]))
    

def results(cl):
    if cl.formset:
        for res, form in zip(cl.result_list, cl.formset.forms):
            yield list(thumbnails_for_result(cl, res, form))
    else:
        for res in cl.result_list:
            yield list(thumbnails_for_result(cl, res, None))

def thumbnail_result_list(context, cl):
    if context.has_key('STATIC_URL'):
        static_url = 'STATIC_URL'
    else:
        static_url = 'MEDIA_URL'
    result_list = list(results(cl))
    if len(result_list) % 4:
        empty_spaces = range(4 - (len(result_list) % 4))
    else:
        empty_spaces = []
    return {'cl': cl,
            'results': result_list,
            'empty_spaces': empty_spaces,
            'STATIC_URL': context[static_url]}
thumbnail_result_list = register.inclusion_tag("admin/massmedia/change_list_results.html", takes_context=True)(thumbnail_result_list)
コード例 #54
0
            # Insert "smart" pagination links, so that there are always ON_ENDS
            # links at either end of the list of pages, and there are always
            # ON_EACH_SIDE links at either end of the "current page" link.
            page_range = []
            if page_num > (ON_EACH_SIDE + ON_ENDS):
                page_range.extend(range(0, ON_EACH_SIDE - 1))
                page_range.append(DOT)
                page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
            else:
                page_range.extend(range(0, page_num + 1))
            if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
                page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
                page_range.append(DOT)
                page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
            else:
                page_range.extend(range(page_num + 1, paginator.num_pages))
    return {
        'cl': cl,
        'pagination_required': pagination_required,
        'ALL_VAR': ALL_VAR,
        '1': 1,
        'has_change_permission': has_change_permission,
        "previous": cl.page_num - 1 if current_page.has_previous() else 0,
        "has_previous": current_page.has_previous(),
        "next": cl.page_num + 1 if current_page.has_next() else page_num - 1,
        "has_next": current_page.has_next(),
        "page_range": page_range,
    }

pagination = register.inclusion_tag('admin/pagination.html')(pagination)
コード例 #55
0
ファイル: admin_list.py プロジェクト: leeight/Tangram-tools
                page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
                page_range.append(DOT)
                page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
            else:
                page_range.extend(range(page_num + 1, paginator.num_pages))

    need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
    return {
        'cl': cl,
        'pagination_required': pagination_required,
        'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
        'page_range': page_range,
        'ALL_VAR': ALL_VAR,
        '1': 1,
    }
pagination = register.inclusion_tag('admin/pagination.html')(pagination)

def result_headers(cl):
    """
    Generates the list column headers.
    """
    lookup_opts = cl.lookup_opts

    for i, field_name in enumerate(cl.list_display):
        header, attr = label_for_field(field_name, cl.model,
            model_admin = cl.model_admin,
            return_attr = True
        )
        if attr:
            # if the field is the action checkbox: no sorting and special class
            if field_name == 'action_checkbox':
コード例 #56
0
        'rate_plans':
        rate_plans,
        'occupancies': [(x, f"{x} " + _('prices:page:ppl'))
                        for x in range(1, RATES_MAX_OCCUPANCY)],
        'phone_codes':
        sorted(select_phone_codes(), key=lambda x: x[0]),
        'rooms':
        select_rooms(house, room_types),
        'close_reasons':
        RoomCloseReasons.choices(),
        'policies':
        select_policies(house, rate_plans),
    }


register.inclusion_tag('board/top.reservation_create.html',
                       takes_context=True)(reservation_shortcut_menu)


@inject.autoparams('roomtypes_repo')
def select_room_types(house: 'House', user: '******',
                      roomtypes_repo: RoomTypesRepo) -> List[RoomType]:
    try:
        return roomtypes_repo.select(house, user=user)
    except Exception as err:
        Logger.warning(
            __name__,
            f"Error select Room Types for House ID={house.id} : {err}")
    return []


@inject.autoparams('prices_repo')