bijoe/bijoe/forms.py

88 lines
3.1 KiB
Python

# bijoe - BI dashboard
# Copyright (C) 2015 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import datetime
from django import forms
from django.utils.translation import ugettext as _
from django_select2.forms import Select2MultipleWidget
class DateRangeWidget(forms.MultiWidget):
def __init__(self, attrs=None):
attrs2 = {'type': 'date'}
if attrs:
attrs2.update(attrs)
widgets = (
forms.DateInput(attrs=attrs2.copy()),
forms.DateInput(attrs=attrs2.copy()),
)
super(DateRangeWidget, self).__init__(widgets, attrs=attrs)
def decompress(self, value):
if not value:
return None, None
return value
class DateRangeField(forms.MultiValueField):
widget = DateRangeWidget
def __init__(self, *args, **kwargs):
# Or define a different message for each field.
fields = (
forms.DateField(required=False),
forms.DateField(required=False),
)
super(DateRangeField, self).__init__(fields=fields, require_all_fields=False, *args,
**kwargs)
def compress(self, values):
return values
class CubeForm(forms.Form):
def __init__(self, *args, **kwargs):
self.cube = cube = kwargs.pop('cube')
super(CubeForm, self).__init__(*args, **kwargs)
# filters
for dimension in cube.dimensions:
if not dimension.filter:
continue
field_name = 'filter__%s' % dimension.name
if dimension.type is datetime.date:
self.fields[field_name] = DateRangeField(
label=dimension.label.capitalize(), required=False)
else:
self.fields[field_name] = forms.MultipleChoiceField(
label=dimension.label.capitalize(),
choices=dimension.members,
required=False,
widget=Select2MultipleWidget())
# group by
choices = [(dimension.name, dimension.label) for dimension in cube.dimensions
if dimension.type not in (datetime.datetime, datetime.date)]
self.fields['drilldown'] = forms.MultipleChoiceField(
label=_('Group by'), choices=choices, required=False, widget=Select2MultipleWidget())
# measures
choices = [(measure.name, measure.label) for measure in cube.measures]
self.fields['measures'] = forms.MultipleChoiceField(
label=_('Measures'), choices=choices, widget=Select2MultipleWidget())