pagination_types.py 2.15 KB
#-*- coding:utf-8 -*-

from datetime import datetime
from django.contrib.auth.models import User
from django.forms import *
from dictionary.models import History, Lexeme, visible_vocabularies

types = {}

def lexeme_history_list(params, user):
  objects = History.objects.exclude(lexeme=None).distinct().values(
    'lexeme', 'user', 'transaction_began')
  lexemes = Lexeme.objects.filter(
    owner_vocabulary__in=visible_vocabularies(user)).exclude(entry='')
  for field, lookup, value in params['filters']:
    if field == 'user':
      if lookup == 'eq':
        objects = objects.filter(user__pk=value)
      elif lookup == 'ne':
        objects = objects.exclude(user__username=value)
    if field == 'time':
      try:
        date = datetime.strptime(value, '%d.%m.%Y')
        if lookup == 'from':
          objects = objects.filter(transaction_began__gte=date)
        elif lookup == 'to':
          objects = objects.filter(transaction_began__lte=date)
      except ValueError:
        pass

  objects = objects.filter(lexeme__in=lexemes)
  objects = objects.order_by(params['order_by'])
  return objects

class LexemeFilterFieldForm(Form):
  field = ChoiceField(
    choices=[], label=u'', widget=Select(attrs={'class': 'field-choice'}))

  def __init__(self, **kwargs):
    super(LexemeFilterFieldForm, self).__init__(**kwargs)
    filters = LEXEME_HISTORY_FILTERS
    choices = [(key, value[0]) for key, value in filters.iteritems()]
    self.fields['field'].choices = choices

class UserFilterForm(Form):
  user = ModelChoiceField(
    queryset=User.objects.order_by('username'), label=u'',
    widget=Select(attrs={'class': 'value'}))

class TimeFilterForm(Form):
  time = DateField(input_formats=['%d.%m.%Y'], label=u'',
    widget=DateInput(attrs={'class': 'datepicker value'}))

LEXEME_HISTORY_FILTERS = {
  'user': (
    u'Użytkownik',
    [('eq', u'równy')],
    UserFilterForm,
  ),
  'time': (
    u'Data',
    [('from', u'od'), ('to', u'do')],
    TimeFilterForm,
  ),
}

def dummy_perm(user, object, action):
  return True

types['lexeme_history'] = (
  lexeme_history_list,
  'lexeme_history_item.html',
  dummy_perm,
  {},
  LEXEME_HISTORY_FILTERS,
  LexemeFilterFieldForm,
)