ajax.py 1.55 KB
# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from common.decorators import ajax, AjaxError
from dictionary.models import Vocabulary


@ajax(method='post', permission_required='dictionary.manage_vocabulary')
def add_vocabulary(request, name):
    if not name:
        raise AjaxError(_(u'dictionary name can\'t be empty!'))
    if Vocabulary.objects.filter(id=name):
        raise AjaxError(_(u'a dictionary with this name already exists!'))
    vocab = Vocabulary.objects.create(id=name)
    vocab.managers.add(request.user)  # add
    return {}


# nieużywane
@ajax(method='get', permission_required='dictionary.manage_vocabulary')
def vocabulary_permissions(request, vocab_id):
    vocab = Vocabulary.objects.get(id=vocab_id)
    return {
        'managers': list(vocab.all_managers().values_list('pk', flat=True)),
        'viewers': list(vocab.all_viewers().values_list('pk', flat=True)),
        'editors': list(vocab.editors.values_list('pk', flat=True)),
    }


@ajax(method='post', permission_required='dictionary.manage_vocabulary')
def set_vocabulary_permission(request, name, user_id, perm, on):
    vocab = Vocabulary.objects.get(id=name)
    user = User.objects.get(pk=user_id)
    if perm == 'view':
        related_manager = vocab.viewers
    elif perm == 'change':
        related_manager = vocab.editors
    else:  # type == 'manage'
        related_manager = vocab.managers
    if on:
        related_manager.add(user)  # add
    else:
        related_manager.remove(user)  # add
    return {}