views.py 2.88 KB
# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import permission_required
from django.core.urlresolvers import reverse
from common.decorators import render
from dictionary.models import get_exclusion_classes, Vocabulary
from patterns.models import InflectionType, BaseFormLabel, PatternType
from patterns.ajax_pattern_view import PatternQuery


def common_pattern_js_vars(request, reader=False):
    inflection_type_options = [
        (it.symbol, it.symbol) for it in InflectionType.objects.all()]
    base_form_labels = dict(
        (pt.id, list(pt.base_form_labels.values_list('id', flat=True)))
        for pt in PatternType.objects.all())
    bfl_symbols = dict(BaseFormLabel.objects.values_list('id', 'symbol'))
    js_vars = {
        'ajax_get_page': reverse('get_patterns'),
        'ajax_search_index': reverse('patterns_search_index'),
        'ajax_row_index': reverse('patterns_row_index'),
        'ajax_pattern_preview': reverse('pattern_preview'),
        'ajax_get_name': reverse('get_name'),
        'inflection_type_options': inflection_type_options,
        'pattern_type_options': PatternType.options(),
        'base_form_labels': base_form_labels,
        'bfl_symbols': bfl_symbols,
        'initial_columns': PatternQuery.default_columns,
    }
    session_prefix = ('reader_' if reader else '') + 'pattern-'
    session_variables = ('sort_rules', 'columns')
    js_vars.update(dict(
        (var, request.session[session_prefix + var])
        for var in session_variables
        if (session_prefix + var) in request.session))
    return js_vars


@permission_required('patterns.view_pattern')
@render('pattern_view.html')
def pattern_view(request):
    editable_vocabs = Vocabulary.editable_vocabularies(request.user)
    vocabs = {}
    for v in editable_vocabs:
        vocabs.update(dict((str(q.pk), v.id) for q in v.qualifiers.all()))
    js_vars = common_pattern_js_vars(request)
    js_vars.update({
        'ajax_edit_form': reverse('pattern_edit_form'),
        'ajax_update_pattern': reverse('update_pattern'),
        'ajax_new_ending_row': reverse('new_ending_row'),
        'ajax_new_ending_table_row': reverse('new_ending_table_row'),
        'ajax_create_pattern': reverse('create_pattern'),
        'ajax_clone_pattern': reverse('clone_pattern'),
        'ajax_history_table': reverse('pattern_table'),
        'ajax_save_filter': reverse('save_filter'),
        'ajax_get_filters': reverse('get_filters'),
        'ajax_delete_filter': reverse('delete_filter'),
        'exclusion_classes': get_exclusion_classes(),
        'auto_search': request.user.usersettings.incremental_search,
        'vocabs': vocabs,
    })
    return {'js_vars': js_vars}


@render('pattern_reader_view.html')
def pattern_reader_view(request):
    js_vars = common_pattern_js_vars(request, reader=True)
    js_vars.update({
        'auto_search': True,
        'vocabs': {},
    })
    return {'js_vars': js_vars}