Esempio n. 1
0
def generateSettings(values, imports=[]):
    m_values, m_imports = magiCirclesGeneratedSettings(values)
    # Existing values have priority
    # Dicts and lists get merged
    for key, value in values.items():
        if isinstance(value, list):
            m_values[key] = value + m_values.get(key, [])
        elif isinstance(value, dict):
            d = m_values.get(key, {})
            d.update(value)
            m_values[key] = d
        else:
            m_values[key] = value

    # Resort latest news if needed
    if m_values.get('LATEST_NEWS', []):
        m_values['LATEST_NEWS'].sort(key=lambda news: int(news.get('priority', 1)) * -1)

    imports = m_imports + imports

    s = u'\
# -*- coding: utf-8 -*-\n\
import datetime\n\
' + u'\n'.join(listUnique(imports)) + '\n\
' + u'\n'.join([
    u'{key} = {value}'.format(key=key, value=unicode(value))
    for key, value in m_values.items()
]) + u'\n\
GENERATED_DATE = datetime.datetime.fromtimestamp(' + unicode(time.time()) + u')\n\
'
    with open(django_settings.BASE_DIR + '/' + django_settings.SITE + '_project/generated_settings.py', 'w') as f:
        f.write(s.encode('utf8'))
        f.close()
Esempio n. 2
0
 def get_displayed_timezones(self, name):
     timezones = ['Local time']
     saved_timezone = getattr(self, u'_{}_timezone'.format(name), None)
     if saved_timezone:
         timezones.append(saved_timezone)
     default_timezones = getattr(self, u'{}_DEFAULT_TIMEZONES'.format(name.upper()), None)
     if default_timezones:
         timezones += default_timezones
     return listUnique(timezones)
Esempio n. 3
0
def displayNames(item):
    """
    Returns the list of displayable names from an item
    """
    return listUnique([
        name for name in [
            unicode(item.t_name),
            item.name,
            item.japanese_name,
        ] if name
    ])
Esempio n. 4
0
def displayNamesRomajiFirst(item):
    """
    Returns the list of displayable names from an item, with priority to romaji is exists
    """
    language = get_language()
    if language == 'ja':
        names = [
            item.japanese_name or item.name,
        ]
    elif language in ['kr', 'zh-hant', 'zh-hans']:
        names = [
            item.japanese_name or item.name,
            item.names.get(language, None),
        ]
    else:
        names = [
            item.romaji_name or item.name,
            unicode(item.t_name),
            item.names.get('ja', None),
        ]
    return listUnique([name for name in names if name])
Esempio n. 5
0
 def get_field_translation_sources(self, field_name):
     return listUnique(getattr(self, u'{}_SOURCE_LANGUAGES'.format(
         field_name.upper()), []) + ['en'])
Esempio n. 6
0
def list_view(request,
              name,
              collection,
              ajax=False,
              extra_filters={},
              shortcut_url=None,
              **kwargs):
    """
    View function for any page that lists data, such as cards. Handles pagination and context variables.
    name: The string that corresponds to the view (for instance 'cards' for the '/cards/' view)
    """
    context = collection.list_view.get_global_context(request)
    collection.list_view.check_permissions(request, context)
    context['plural_name'] = collection.plural_name
    page = 0
    page_size = collection.list_view.page_size
    if 'page_size' in request.GET:
        try:
            page_size = int(request.GET['page_size'])
        except ValueError:
            pass
        if page_size > 500: page_size = 500
    filters = _get_filters(request.GET, extra_filters)
    queryset = collection.list_view.get_queryset(collection.queryset, filters,
                                                 request)

    ordering = None
    if 'ordering' in request.GET and request.GET['ordering']:
        reverse = ('reverse_order' in request.GET
                   and request.GET['reverse_order']) or not request.GET or len(
                       request.GET) == 1
        prefix = '-' if reverse else ''
        ordering = [
            prefix + ordering
            for ordering in request.GET['ordering'].split(',')
        ]
        if (collection.list_view.show_relevant_fields_on_ordering
                and request.GET['ordering'] != ','.join(
                    collection.list_view.plain_default_ordering_list)):
            context['show_relevant_fields_on_ordering'] = True
            context['plain_ordering'] = [
                o[1:] if o.startswith('-') else o for o in ordering
            ]

    if collection.list_view.filter_form:
        if len(request.GET) > 1 or (len(request.GET) == 1
                                    and 'page' not in request.GET):
            context['filter_form'] = collection.list_view.filter_form(
                filters, request=request, ajax=ajax, collection=collection)
        else:
            context['filter_form'] = collection.list_view.filter_form(
                request=request, ajax=ajax, collection=collection)
        if hasattr(context['filter_form'], 'filter_queryset'):
            queryset = context['filter_form'].filter_queryset(
                queryset, filters, request)
        else:
            queryset = filter_ids(queryset, request)
    else:
        queryset = filter_ids(queryset, request)

    if not ordering:
        if ('filter_form' in context
                and 'ordering' in context['filter_form'].fields
                and context['filter_form'].fields['ordering'].initial):
            reverse = True
            if 'reverse_order' in context['filter_form'].fields:
                reverse = context['filter_form'].fields[
                    'reverse_order'].initial
            ordering = [
                u'{}{}'.format(
                    '-' if reverse else '',
                    context['filter_form'].fields['ordering'].initial,
                )
            ]
        else:
            ordering = collection.list_view.default_ordering.split(',')
    queryset = queryset.order_by(*ordering)

    if collection.list_view.distinct:
        queryset = queryset.distinct()
    context['total_results'] = queryset.count()
    context['total_results_sentence'] = _(
        '1 {object} matches your search:').format(
            object=collection.title.lower(
            )) if context['total_results'] == 1 else _(
                '{total} {objects} match your search:').format(
                    total=context['total_results'],
                    objects=collection.plural_title.lower())

    if 'page' in request.GET and request.GET['page']:
        page = int(request.GET['page']) - 1
        if page < 0:
            page = 0
    queryset = queryset[(page * page_size):((page * page_size) + page_size)]

    if 'filter_form' in context and not ajax:
        cuteFormFieldsForContext(
            collection.list_view.filter_cuteform,
            context,
            form=context['filter_form'],
            prefix='#sidebar-wrapper ',
            ajax=ajax,
        )

    # Will display a link to see the other results instead of the pagination button
    context['ajax_modal_only'] = False
    if 'ajax_modal_only' in request.GET:
        context['ajax_modal_only'] = True
        context['filters_string'] = '&'.join([
            '{}={}'.format(k, v) for k, v in filters.items()
            if k != 'ajax_modal_only'
        ])
        context['remaining'] = context['total_results'] - page_size

    # Will still show top buttons at the top, first page only
    context[
        'ajax_show_top_buttons'] = ajax and 'ajax_show_top_buttons' in request.GET and page == 0

    if shortcut_url is not None:
        context['shortcut_url'] = shortcut_url

    # Ajax items reloader
    if not ajax and collection.list_view.auto_reloader and collection.list_view.ajax:
        context['ajax_reload_url'] = collection.get_list_url(ajax=True)
        context['reload_urls_start_with'] = [
            u'/{}/edit/'.format(collection.plural_name)
        ]
        if collection.collectible_collections:
            context['reload_urls_start_with'] += [
                cc.get_add_url()
                for cc in collection.collectible_collections.values()
            ]

    # Alt views
    context['view'] = None
    context['alt_view'] = None
    alt_views = dict(collection.list_view.alt_views)
    if 'view' in request.GET and request.GET['view'] in alt_views:
        context['view'] = request.GET['view']
        context['alt_view'] = alt_views[context['view']]
    context['ordering'] = ordering
    context['page_title'] = _(u'{things} list').format(
        things=collection.plural_title)
    context['h1_page_title'] = collection.plural_title
    context['total_pages'] = int(
        math.ceil(context['total_results'] / page_size))
    context['items'] = queryset
    context['page'] = page + 1

    page_buttons = [(0, 'active' if page == 0 else None)]
    if page > 2:
        page_buttons.append((-1, 'disabled'))
    if (page - 1) > 0:
        page_buttons.append((page - 1, None))
    page_buttons.append((page, 'active'))
    if (page + 1) < (context['total_pages'] - 1):
        page_buttons.append((page + 1, None))
    if page < (context['total_pages'] - 3):
        page_buttons.append((-2, 'disabled'))
    page_buttons.append(
        (context['total_pages'] - 1,
         'active' if page == (context['total_pages'] - 1) else None))
    context['displayed_page_buttons'] = listUnique(page_buttons)
    if request.path and request.path != '/':
        context['next_page_url'] = u'/ajax{}'.format(request.path)
    else:
        context['next_page_url'] = u'/ajax/{}/'.format(collection.plural_name)
    context['is_last_page'] = context['page'] == context['total_pages']
    context['page_size'] = page_size
    context['show_no_result'] = not ajax or context['ajax_modal_only']
    context[
        'show_search_results'] = collection.list_view.show_search_results and bool(
            request.GET)
    context['show_owner'] = 'show_owner' in request.GET
    context['get_started'] = 'get_started' in request.GET
    context['name'] = name
    context['title'] = collection.title
    context['reportable'] = collection.reportable
    context['hide_sidebar'] = collection.list_view.hide_sidebar
    context['before_template'] = collection.list_view.before_template
    context['no_result_template'] = collection.list_view.no_result_template
    context['after_template'] = collection.list_view.after_template
    context['item_template'] = collection.list_view.item_template
    context['hide_icons'] = collection.list_view.hide_icons
    context[
        'item_blocked_template'] = collection.list_view.item_blocked_template
    if context['alt_view'] and 'template' in context['alt_view']:
        context['item_template'] = context['alt_view']['template']
    context['item_padding'] = collection.list_view.item_padding
    context['show_title'] = collection.list_view.show_title
    context['plural_title'] = collection.plural_title
    context['show_items_names'] = collection.list_view.show_items_names
    context['show_items_titles'] = collection.list_view.show_items_titles
    context['lowercase_plural_title'] = collection.plural_title.lower()
    context['ajax_pagination'] = collection.list_view.ajax
    context[
        'ajax_pagination_callback'] = collection.list_view.ajax_pagination_callback
    if not ajax or context['ajax_modal_only']:
        # Should only be called once
        context['ajax_callback'] = collection.list_view.ajax_callback
    context['ajax'] = ajax
    context['js_files'] = collection.list_view.js_files
    context['share_image'] = _get_share_image(context, collection.list_view)
    context['full_width'] = collection.list_view.full_width
    if context['alt_view'] and 'full_width' in context['alt_view']:
        context['full_width'] = context['alt_view']['full_width']
    context['display_style'] = collection.list_view.display_style
    if context['alt_view'] and 'display_style' in context['alt_view']:
        context['display_style'] = context['alt_view']['display_style']
    context[
        'display_style_table_classes'] = collection.list_view.display_style_table_classes
    context[
        'display_style_table_fields'] = collection.list_view.display_style_table_fields
    if context['alt_view'] and 'display_style_table_fields' in context[
            'alt_view']:
        context['display_style_table_fields'] = context['alt_view'][
            'display_style_table_fields']
    context['col_break'] = collection.list_view.col_break
    context['per_line'] = int(
        request.GET['max_per_line']) if 'max_per_line' in request.GET and int(
            request.GET['max_per_line']
        ) < collection.list_view.per_line else collection.list_view.per_line
    if context['alt_view'] and 'per_line' in context['alt_view']:
        context['per_line'] = context['alt_view']['per_line']
    context['col_size'] = _get_col_size(context['per_line'])
    context['ajax_item_popover'] = collection.list_view.ajax_item_popover
    context['item_view_enabled'] = collection.item_view.enabled
    context['ajax_item_view_enabled'] = context[
        'item_view_enabled'] and collection.item_view.ajax and not context[
            'ajax_item_popover']
    context['include_below_item'] = False  # May be set to true below
    context['collection'] = collection

    if context['display_style'] == 'table':
        context[
            'table_fields_headers'] = collection.list_view.table_fields_headers(
                context['display_style_table_fields'], view=context['view'])
        context[
            'table_fields_headers_sections'] = collection.list_view.table_fields_headers_sections(
                view=context['view'])

    if not ajax or context['ajax_show_top_buttons']:
        context['top_buttons'] = collection.list_view.top_buttons(
            request, context)
        context['top_buttons_total'] = len([
            True for b in context['top_buttons'].values()
            if b['show'] and b['has_permissions']
        ])
        if context['top_buttons_total']:
            context['top_buttons_col_size'] = _get_col_size(
                context['top_buttons_total'])

    context['show_item_buttons'] = collection.list_view.show_item_buttons
    for i, item in enumerate(queryset):
        item.request = request
        if collection.list_view.foreach_items:
            collection.list_view.foreach_items(i, item, context)
        if context.get('show_relevant_fields_on_ordering', False):
            context['include_below_item'] = True
            item.relevant_fields_to_show = collection.list_view.ordering_fields(
                item, only_fields=context['plain_ordering'], request=request)
        if context['display_style'] == 'table':
            item.table_fields = collection.list_view.table_fields(
                item,
                only_fields=context['display_style_table_fields'],
                force_all_fields=True,
                request=request)
        item.buttons_to_show = collection.list_view.buttons_per_item(
            request, context, item)
        if 'only_show_buttons' in request.GET:
            only_show_buttons = request.GET['only_show_buttons'].split(',')
            for button_name, button in item.buttons_to_show.items():
                if button_name not in only_show_buttons:
                    button['show'] = False
        item.show_item_buttons_justified = collection.list_view.show_item_buttons_justified
        item.show_item_buttons_as_icons = collection.list_view.show_item_buttons_as_icons
        item.show_item_buttons_in_one_line = collection.list_view.show_item_buttons_in_one_line
        if collection.list_view.show_item_buttons and [
                True for b in item.buttons_to_show.values()
                if b['show'] and b['has_permissions']
        ]:
            context['include_below_item'] = True
        if request.user.is_authenticated() and collection.blockable:
            if item.owner_id in request.user.preferences.cached_blocked_ids:
                item.blocked = True
                try:
                    username = item.owner.username
                except AttributeError:
                    username = _('this user')
                item.blocked_message = _(u'You blocked {username}.').format(
                    username=username)
                item.unblock_button = _(u'Unblock {username}').format(
                    username=username)
            elif item.owner_id in request.user.preferences.cached_blocked_by_ids:
                item.blocked_by_owner = True

    collection.list_view.extra_context(context)

    if ajax:
        context['include_template'] = 'collections/list_page'
        if context['ajax_modal_only'] and context['ajax_pagination_callback']:
            context['ajax_callback'] = context['ajax_pagination_callback']
        return render(request, 'ajax.html', context)
    return render(request, 'collections/list_view.html', context)
def list_view(request, name, collection, ajax=False, extra_filters={}, shortcut_url=None, **kwargs):
    """
    View function for any page that lists data, such as cards. Handles pagination and context variables.
    name: The string that corresponds to the view (for instance 'cards' for the '/cards/' view)
    """
    context = collection.list_view.get_global_context(request)
    collection.list_view.check_permissions(request, context)
    context['plural_name'] = collection.plural_name
    page = 0

    # Alt views
    context['view'] = None
    context['alt_view'] = None
    alt_views = dict(collection.list_view.alt_views)
    page_size = collection.list_view.page_size
    if 'view' in request.GET and request.GET['view'] in alt_views:
        context['view'] = request.GET['view']
        context['alt_view'] = alt_views[context['view']]
    if context['alt_view'] and 'page_size' in context['alt_view']:
        page_size = context['alt_view']['page_size']

    if 'page_size' in request.GET:
        try: page_size = int(request.GET['page_size'])
        except ValueError: pass
        if page_size > 500: page_size = 500
    filters = _get_filters(request.GET, extra_filters)
    queryset = collection.list_view.get_queryset(collection.queryset, filters, request)

    show_relevant_fields_on_ordering = collection.list_view.show_relevant_fields_on_ordering
    if context['alt_view'] and 'show_relevant_fields_on_ordering' in context['alt_view']:
        show_relevant_fields_on_ordering = context['alt_view']['show_relevant_fields_on_ordering']

    ordering = None
    if 'ordering' in request.GET and request.GET['ordering']:
        reverse = ('reverse_order' in request.GET and request.GET['reverse_order']) or not request.GET or len(request.GET) == 1
        prefix = '-' if reverse else ''
        ordering = [prefix + ordering for ordering in request.GET['ordering'].split(',')]
        if (show_relevant_fields_on_ordering
            and request.GET['ordering'] != ','.join(collection.list_view.plain_default_ordering_list)):
            context['show_relevant_fields_on_ordering'] = True
            context['plain_ordering'] = [o[1:] if o.startswith('-') else o for o in ordering]

    filled_filter_form = False
    if collection.list_view.filter_form:
        if len([k for k in request.GET.keys() if k not in GET_PARAMETERS_NOT_FROM_FORM]) > 0:
            context['filter_form'] = collection.list_view.filter_form(filters, request=request, ajax=ajax, collection=collection)
            filled_filter_form = True
        else:
            context['filter_form'] = collection.list_view.filter_form(request=request, ajax=ajax, collection=collection)
        if hasattr(context['filter_form'], 'filter_queryset'):
            queryset = context['filter_form'].filter_queryset(queryset, filters, request)
        else:
            queryset = filter_ids(queryset, request)
    else:
        queryset = filter_ids(queryset, request)

    if not ordering:
        if ('filter_form' in context
            and 'ordering' in context['filter_form'].fields
            and context['filter_form'].fields['ordering'].initial):
            reverse = True
            if 'reverse_order' in context['filter_form'].fields:
                reverse = context['filter_form'].fields['reverse_order'].initial
            ordering = [
                u'{}{}'.format(
                    '-' if reverse else '',
                    ordering_field,
                ) for ordering_field in context['filter_form'].fields['ordering'].initial.split(',')
            ]
        else:
            ordering = collection.list_view.default_ordering.split(',')
    queryset = queryset.order_by(*ordering)

    if collection.list_view.distinct:
        queryset = queryset.distinct()
    context['total_results'] = queryset.count()
    context['total_results_sentence'] = _('1 {object} matches your search:').format(object=collection.title.lower()) if context['total_results'] == 1 else _('{total} {objects} match your search:').format(total=context['total_results'], objects=collection.plural_title.lower())

    if 'page' in request.GET and request.GET['page']:
        page = int(request.GET['page']) - 1
        if page < 0:
            page = 0
    queryset = queryset[(page * page_size):((page * page_size) + page_size)]

    if 'filter_form' in context and not ajax:
        cuteFormFieldsForContext(
            collection.list_view.filter_cuteform,
            context, form=context['filter_form'],
            prefix='#sidebar-wrapper ',
            ajax=ajax,
        )

    # Will display a link to see the other results instead of the pagination button
    context['ajax_modal_only'] = False
    if 'ajax_modal_only' in request.GET:
        context['ajax_modal_only'] = True
        context['filters_string'] = '&'.join(['{}={}'.format(k, v) for k, v in filters.items() if k != 'ajax_modal_only'])
        context['remaining'] = context['total_results'] - page_size

    # Will still show top buttons at the top, first page only
    context['ajax_show_top_buttons'] = ajax and 'ajax_show_top_buttons' in request.GET and page == 0

    if shortcut_url is not None:
        context['shortcut_url'] = shortcut_url

    context['ordering'] = ordering
    context['page_title'] = _(u'{things} list').format(things=collection.plural_title)
    context['h1_page_title'] = collection.plural_title
    context['total_pages'] = int(math.ceil(context['total_results'] / page_size))
    context['items'] = queryset
    context['page'] = page + 1

    page_buttons = [(0, 'active' if page == 0 else None)]
    if page > 2:
        page_buttons.append((-1, 'disabled'))
    if (page - 1) > 0:
        page_buttons.append((page - 1, None))
    page_buttons.append((page, 'active'))
    if (page + 1) < (context['total_pages'] - 1):
        page_buttons.append((page + 1, None))
    if page < (context['total_pages'] - 3):
        page_buttons.append((-2, 'disabled'))
    page_buttons.append((context['total_pages'] - 1, 'active' if page == (context['total_pages'] - 1) else None))
    context['displayed_page_buttons'] = listUnique(page_buttons)
    if request.path and request.path != '/':
        context['next_page_url'] = u'/ajax{}'.format(request.path)
    else:
        context['next_page_url'] = u'/ajax/{}/'.format(collection.plural_name)

    # Ajax items reloader
    if not ajax and collection.list_view.auto_reloader and collection.list_view.ajax:
        context['ajax_reload_url'] = context['next_page_url']
        context['reload_urls_start_with'] = [u'/{}/edit/'.format(collection.plural_name)];
        if collection.collectible_collections:
            context['reload_urls_start_with'] += [cc.get_add_url() for cc in collection.collectible_collections.values()]

    context['is_last_page'] = context['page'] == context['total_pages']
    context['page_size'] = page_size
    context['show_no_result'] = not ajax or context['ajax_modal_only']
    context['show_search_results'] = collection.list_view.show_search_results and filled_filter_form
    context['show_owner'] = 'show_owner' in request.GET
    context['get_started'] = 'get_started' in request.GET
    context['name'] = name
    context['title'] = collection.title
    context['reportable'] = collection.reportable
    context['hide_sidebar'] = collection.list_view.hide_sidebar
    context['before_template'] = collection.list_view.before_template
    context['no_result_template'] = collection.list_view.no_result_template
    context['after_template'] = collection.list_view.after_template
    context['item_template'] = collection.list_view.item_template
    context['hide_icons'] = collection.list_view.hide_icons
    context['item_blocked_template'] = collection.list_view.item_blocked_template
    if context['alt_view'] and 'template' in context['alt_view']:
        context['item_template'] = context['alt_view']['template']
    context['item_padding'] = collection.list_view.item_padding
    context['show_title'] = collection.list_view.show_title
    context['plural_title'] = collection.plural_title
    context['show_items_names'] = collection.list_view.show_items_names
    context['lowercase_plural_title'] = collection.plural_title.lower()
    context['ajax_pagination'] = collection.list_view.ajax
    context['ajax_pagination_callback'] = collection.list_view.ajax_pagination_callback
    if not ajax or context['ajax_modal_only']:
        # Should only be called once
        context['ajax_callback'] = collection.list_view.ajax_callback
    context['ajax'] = ajax
    context['js_files'] = collection.list_view.js_files
    context['share_image'] = _get_share_image(context, collection.list_view)
    context['full_width'] = collection.list_view.full_width
    if context['alt_view'] and 'full_width' in context['alt_view']:
        context['full_width'] = context['alt_view']['full_width']
    context['display_style'] = collection.list_view.display_style
    if context['alt_view'] and 'display_style' in context['alt_view']:
        context['display_style'] = context['alt_view']['display_style']
    if context['display_style'] == 'table' and context['item_template'] == 'default_item_in_list':
        context['item_template'] = 'default_item_table_view'
    context['display_style_table_classes'] = collection.list_view.display_style_table_classes
    context['display_style_table_fields'] = collection.list_view.display_style_table_fields
    if context['alt_view'] and 'display_style_table_fields' in context['alt_view']:
        context['display_style_table_fields'] = context['alt_view']['display_style_table_fields']
    context['col_break'] = collection.list_view.col_break
    context['per_line'] = int(request.GET['max_per_line']) if 'max_per_line' in request.GET and int(request.GET['max_per_line']) < collection.list_view.per_line else collection.list_view.per_line
    if context['alt_view'] and 'per_line' in context['alt_view']:
        context['per_line'] = context['alt_view']['per_line']
    context['col_size'] = _get_col_size(context['per_line'])
    context['ajax_item_popover'] = collection.list_view.ajax_item_popover
    context['item_view_enabled'] = collection.item_view.enabled
    context['ajax_item_view_enabled'] = context['item_view_enabled'] and collection.item_view.ajax and not context['ajax_item_popover']
    context['include_below_item'] = False # May be set to true below
    context['collection'] = collection

    if context['display_style'] == 'table':
        context['table_fields_headers'] = collection.list_view.table_fields_headers(context['display_style_table_fields'], view=context['view'])
        context['table_fields_headers_sections'] = collection.list_view.table_fields_headers_sections(view=context['view'])

    if not ajax or context['ajax_show_top_buttons']:
        context['top_buttons'] = collection.list_view.top_buttons(request, context)
        context['top_buttons_total'] = len([True for b in context['top_buttons'].values() if b['show'] and b['has_permissions']])
        if context['top_buttons_total']:
            context['top_buttons_col_size'] = _get_col_size(context['top_buttons_total'])

    context['show_item_buttons'] = collection.list_view.show_item_buttons
    for i, item in enumerate(queryset):
        item.request = request
        if collection.list_view.foreach_items:
            collection.list_view.foreach_items(i, item, context)
        if context.get('show_relevant_fields_on_ordering', False):
            context['include_below_item'] = True
            item.relevant_fields_to_show = collection.list_view.ordering_fields(item, only_fields=context['plain_ordering'], request=request)
        if context['display_style'] == 'table':
            item.table_fields = collection.list_view.table_fields(item, only_fields=context['display_style_table_fields'], force_all_fields=True, request=request)
        item.buttons_to_show = collection.list_view.buttons_per_item(request, context, item)
        if 'only_show_buttons' in request.GET:
            only_show_buttons = request.GET['only_show_buttons'].split(',')
            for button_name, button in item.buttons_to_show.items():
                if button_name not in only_show_buttons:
                    button['show'] = False
        item.show_item_buttons_justified = collection.list_view.show_item_buttons_justified
        item.show_item_buttons_as_icons = collection.list_view.show_item_buttons_as_icons
        item.show_item_buttons_in_one_line = collection.list_view.show_item_buttons_in_one_line
        if collection.list_view.show_item_buttons and [True for b in item.buttons_to_show.values() if b['show'] and b['has_permissions']]:
            context['include_below_item'] = True
        if request.user.is_authenticated() and collection.blockable:
            if item.owner_id in request.user.preferences.cached_blocked_ids:
                item.blocked = True
                try:
                    username = item.owner.username
                except AttributeError:
                    username = _('this user')
                item.blocked_message = _(u'You blocked {username}.').format(username=username)
                item.unblock_button = _(u'Unblock {username}').format(username=username)
            elif item.owner_id in request.user.preferences.cached_blocked_by_ids:
                item.blocked_by_owner = True

    collection.list_view.extra_context(context)

    if ajax:
        context['include_template'] = 'collections/list_page'
        if context['ajax_modal_only'] and context['ajax_pagination_callback']:
            context['ajax_callback'] = context['ajax_pagination_callback']
        return render(request, 'ajax.html', context)
    return render(request, 'collections/list_view.html', context)
Esempio n. 8
0
def generate_settings():
    print 'Cache schools'
    schools = OrderedDict([
        (school.pk, {
            'name': school.name,
            'names': school.names,
            'white_image': school.white_image_url or school.image_url,
            'image': school.image_url,
        })
        for school in models.School.objects.all().order_by('id')
    ])

    # print 'Add events to latest news'
    # recent_events = models.Event.objects.get(end_date__gte=two_days_ago)
    # latest_news += [{
    #     'title': event.name,
    #     'image': event.image_url,
    #     'url': event.item_url,
    # } for event in recent_events]

    print 'Max statistics'
    try:
        max_statistics = {
            model.collection_name: {
                prefix: {
                    statistic: getattr(model.objects.order_by(u'-{prefix}{statistic}'.format(
                        prefix=prefix, statistic=statistic,
                    ))[0], u'{prefix}{statistic}'.format(
                        prefix=prefix, statistic=statistic,
                    )) for statistic in model.STATISTICS_FIELDS
                } for prefix in ['delta_', 'max_level_']
            } for model in (models.Card, models.Memoir)
        }
    except IndexError:
        max_statistics = {}

    print 'Cache importable fields'
    importable_fields = {}
    for configuration in IMPORT_CONFIGURATION.values() + [ACT_IMPORT_CONFIGURATION]:
        ok_to_edit_fields = configuration.get('dont_erase_existing_value_fields', [])
        imported_fields = listUnique(
            configuration.get('unique_fields', [])
            + configuration.get('fields', [])
            + configuration.get('mapped_fields', []),
        )
        many2many_fields = []
        for field in imported_fields:
            if isinstance(configuration['model']._meta.get_field(field), ManyToManyField):
                many2many_fields.append(field)
        importable_fields[configuration['model'].collection_name] = {
            'imported_fields': imported_fields,
            'ok_to_edit_fields': ok_to_edit_fields,
            'many2many_fields': many2many_fields,
        }

    print 'Save generated settings'
    generateSettings({
        'MAX_STATISTICS': max_statistics,
        'IMPORTABLE_FIELDS': importable_fields,
        'SCHOOLS': schools,
    })