ajax_filters.py 1.38 KB
# -*- coding: utf-8 -*-/home/janek/src/lexeme_forge/dictionary

from common.decorators import ajax, AjaxError
from common.util import json_decode
from dictionary.models import SavedFilter


@ajax(method='post')
def save_filter(request, name, serialized_filter, super=False, force=False):
    existing_filter = SavedFilter.objects.filter(user=request.user, name=name)
    if force or not existing_filter:
        if existing_filter:
            filter = existing_filter[0]
        else:
            filter = SavedFilter()
            filter.name = name
            filter.user = request.user
        filter.serialized_filter = serialized_filter
        filter.super = super
        try:
            filter.save()
        except ValueError as e:
            raise AjaxError(e.message)
    else:
        return {'exists': True}
    return {}


@ajax(method='get')
def get_filters(request):
    filters = [
        {
            'id': 'filter%s' % filter.pk,
            'name': filter.name,
            'params': json_decode(filter.serialized_filter),
        }
        for filter in SavedFilter.objects.filter(user=request.user)]
    return {'filters': filters}


@ajax(method='post')
def delete_filter(request, id):
    filter_id = id[len('filter'):]
    filter = SavedFilter.objects.get(pk=filter_id)
    if filter.user != request.user:
        raise AjaxError('access denied')
    filter.delete()
    return {}