ajax_export.py 1.35 KB
# -*- coding: utf-8 -*-

from common.decorators import ajax, AjaxError, render_ajax
from dictionary.forms import MagicQualifierForm
from dictionary.models import SavedExportData


@render_ajax(template='magic_qualifier_row.html', method='get')
def magic_qualifier_row(request, num):
    return {
        'form': MagicQualifierForm(prefix='magic_%s' % num),
        'num': num,
    }


@ajax(method='post')
def save_export_data(request, name, serialized_data, force=False):
    existing_data = SavedExportData.objects.filter(name=name)
    if force or not existing_data:
        if existing_data:
            data = existing_data[0]
        else:
            data = SavedExportData()
            data.name = name
        data.serialized_data = serialized_data
        try:
            data.save()
        except ValueError as e:
            raise AjaxError(e.data)
    else:
        return {'exists': True}
    return {}


@ajax(method='get')
def get_export_data(request):
    data_list = [{
        'id': 'export%s' % data.pk,
        'name': data.name,
        'json': data.serialized_data,
    }
        for data in SavedExportData.objects.all()]
    return {'data_list': data_list}


@ajax(method='post')
def delete_export_data(request, data_id):
    export_data_id = data_id[len('export'):]
    data = SavedExportData.objects.get(pk=export_data_id)
    data.delete()
    return {}