fef-questionnaire/questionnaire/qprocessors/timeperiod.py

65 lines
2.1 KiB
Python
Raw Permalink Normal View History

2020-02-12 19:12:14 +00:00
from six import text_type as unicodestr
from django.utils.translation import ugettext as _, ugettext_lazy
2016-07-26 21:08:23 +00:00
from .. import add_type, question_proc, answer_proc, AnswerException
perioddict = {
"second" : ugettext_lazy("second(s)"),
"minute" : ugettext_lazy("minute(s)"),
"hour" : ugettext_lazy("hour(s)"),
"day" : ugettext_lazy("day(s)"),
"week" : ugettext_lazy("week(s)"),
"month" : ugettext_lazy("month(s)"),
"year" : ugettext_lazy("year(s)"),
}
@question_proc('timeperiod')
def question_timeperiod(request, question):
cd = question.getcheckdict()
if "units" in cd:
units = cd["units"].split(',')
else:
units = ["day","week","month","year"]
timeperiods = []
if not units:
units = ["day","week","month","year"]
key1 = "question_%s" % question.number
key2 = "question_%s_unit" % question.number
value = request.POST.get(key1, '')
unitselected = request.POST.get(key2, units[0])
for x in units:
if x in perioddict:
2020-02-12 19:12:14 +00:00
timeperiods.append( (x, unicodestr(perioddict[x]), unitselected==x) )
return {
"required" : "required" in cd,
"timeperiods" : timeperiods,
"value" : value,
}
@answer_proc('timeperiod')
def process_timeperiod(question, answer):
2020-02-12 20:31:14 +00:00
if not answer['ANSWER'] or not 'unit' in answer:
raise AnswerException(_(u"Invalid time period"))
period = answer['ANSWER'].strip()
if period:
try:
period = str(int(period))
except ValueError:
raise AnswerException(_(u"Time period must be a whole number"))
unit = answer['unit']
checkdict = question.getcheckdict()
if checkdict and 'units' in checkdict:
units = checkdict['units'].split(',')
else:
units = ('day', 'hour', 'week', 'month', 'year')
if not period and "required" in checkdict:
raise AnswerException(_(u'Field cannot be blank'))
if unit not in units:
raise AnswerException(_(u"Invalid time period"))
return "%s; %s" % (period, unit)
add_type('timeperiod', 'Time Period [input, select]')