views.py 2.38 KB
# Create your views here.

from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.views.decorators.csrf import csrf_exempt
from django_datatables_view.base_datatable_view import BaseDatatableView

from common.decorators import render, ajax
from webapp.models import Expression


@login_required
@render()
def main_page(request):
    js_vars = {
        'ajax_expressions': reverse('expressions'),
        'ajax_expression_info': reverse('expression_info')
    }
    return {'js_vars': js_vars}


@csrf_exempt
@render('expression_info.html')
@ajax(method='get', encode_result=False)
def expression_info(request, id):
    sel_expr = Expression.objects.get(id=id)
    meaning = sel_expr.meaning
    all_exprs = meaning.expressions.filter(main_expression=None).order_by('text')

    return {'sel_expr': sel_expr,
            'meaning': meaning,
            'all_exprs': all_exprs}


class ExpressionsJson(BaseDatatableView):
    model = Expression
    columns = ['text', 'sources', 'category', 'id']
    order_columns = ['text', 'sources', 'meaning__category']
    max_display_length = 100

    def get_initial_queryset(self):
        return Expression.objects.filter(main_expression=None)

    def render_column(self, row, column):
        if column == 'text':
            return u'{0}'.format(row.text)
        elif column == 'sources':
            return u'{0}'.format(', '.join('<a href="%s">%s</a>' % (source.url, source.name)
                                           for source in row.sources.order_by('name')))
        elif column == 'category':
            return u'{0}'.format(row.meaning.category.name)
        else:
            return super(ExpressionsJson, self).render_column(row, column)

    def filter_queryset(self, qs):
        print self.request.GET
        search = self.request.GET.get(u'search[value]', None)
        if search:
            qs = qs.filter(text__contains=search)

        expr = self.request.GET.get(u'columns[0][search][value]', None)
        if expr:
            qs = qs.filter(text__contains=expr)

        source = self.request.GET.get(u'columns[1][search][value]', None)
        if source:
            qs = qs.filter(sources__name__contains=source)

        category = self.request.GET.get(u'columns[2][search][value]', None)
        if category:
            qs = qs.filter(meaning__category__name__contains=category)

        return qs