def render(self, name, value, attrs=None): try: year_val, month_val = value.year, value.month except AttributeError: year_val = month_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name local_attrs = self.build_attrs(id=self.month_field % id_) month_choices = MONTHS.items() month_choices.insert(0, self.none_value) #month_choices.sort() s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) year_choices = [(i, i) for i in self.years] year_choices.insert(0, self.none_value) local_attrs['id'] = self.year_field % id_ s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(select_html) return mark_safe(u'\n'.join(output))
def __init__(self, *args, **kwargs): super(StripePaymentForm, self).__init__(*args, **kwargs) self.fields['card_cvv'].label = "Card CVC" self.fields['card_cvv'].help_text = "Card Verification Code; see rear of card." months = [(m[0], u'%02d - %s' % (m[0], str(m[1]))) for m in sorted(MONTHS.items())] self.fields['card_expiry_month'].choices = months
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] choices = [(i, i) for i in self.years] year_html = self.create_select(name, self.year_field, value, year_val, choices) choices = MONTHS.items() month_html = self.create_select(name, self.month_field, value, month_val, choices) choices = [(i, i) for i in range(1, 32)] day_html = self.create_select(name, self.day_field, value, day_val, choices) format = get_format('DATE_FORMAT') escaped = False output = [] for char in format: if escaped: escaped = False elif char == '\\': escaped = True elif char in 'Yy': output.append(year_html) elif char in 'bFMmNn': output.append(month_html) elif char in 'dj': output.append(day_html) return mark_safe(u'\n'.join(output))
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): if settings.USE_L10N: try: input_format = get_format('DATE_INPUT_FORMATS')[0] v = datetime.datetime.strptime(value, input_format) year_val, month_val, day_val = v.year, v.month, v.day except ValueError: pass else: match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] choices = [(i, i) for i in self.years] year_html = self.create_select(name, self.year_field, value, year_val, choices) choices = MONTHS.items() month_html = self.create_select(name, self.month_field, value, month_val, choices) choices = [(i, i) for i in range(1, 32)] day_html = self.create_select(name, self.day_field, value, day_val, choices) output = [] for field in _parse_date_fmt(): if field == 'year': output.append(year_html) elif field == 'month': output.append(month_html) elif field == 'day': output.append(day_html) return mark_safe(u'\n'.join(output))
def render(self, name, value, attrs=None, extra_context={}): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): if settings.USE_L10N: try: input_format = formats.get_format( 'DATE_INPUT_FORMATS' )[0] v = datetime.datetime.strptime(value, input_format) year_val, month_val, day_val = v.year, v.month, v.day except ValueError: pass else: match = RE_DATE.match(value) if match: year_val, month_val, day_val = map(int, match.groups()) context = self.get_context(name, value, attrs=attrs, extra_context=extra_context) context['year_choices'] = [(i, i) for i in self.years] context['year_val'] = year_val context['month_choices'] = MONTHS.items() context['month_val'] = month_val context['day_choices'] = [(i, i) for i in range(1, 32)] context['day_val'] = day_val return loader.render_to_string(self.template_name, context)
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, str): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name month_choices = list(MONTHS.items()) month_choices.sort() local_attrs = self.build_attrs(id=self.month_field % id_) select_html = Select(choices=month_choices).render(self.month_field % name, month_val, local_attrs) output.append(select_html) day_choices = [(i, i) for i in range(1, 32)] local_attrs['id'] = self.day_field % id_ select_html = Select(choices=day_choices).render(self.day_field % name, day_val, local_attrs) output.append(select_html) year_choices = [(i, i) for i in self.years] local_attrs['id'] = self.year_field % id_ select_html = Select(choices=year_choices).render(self.year_field % name, year_val, local_attrs) output.append(select_html) return mark_safe('\n'.join(output))
def render(self, name, value, attrs=None): try: y_val, m_val = value.year, value.month except AttributeError: y_val = m_val = None if isinstance(value, str): match = RE_DATE.match(value) if match: y_val, m_val, d_val = [int(v) for v in match.groups()] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name month_choices = list(MONTHS.items()) if not (self.required and value): month_choices.append(self.none_value_month) month_choices.sort() local_attrs = self.build_attrs(id=self.month_field % id_) s = Select(choices=month_choices) select_html = s.render(self.month_field % name, m_val, local_attrs) output.append('<div class="date-select">' + select_html + '</div>') year_choices = [(i, i) for i in self.years] if not (self.required and value): year_choices.insert(0, self.none_value_year) local_attrs['id'] = self.year_field % id_ s = Select(choices=year_choices) select_html = s.render(self.year_field % name, y_val, local_attrs) output.append('<div class="date-select">' + select_html + '</div>') return mark_safe(u'\n'.join(output))
def __init__(self, attrs=None): # create choices for days, months, years # example below, the rest snipped for brevity. _widgets = ( widgets.Select(attrs=attrs, choices=MONTHS.items()), # widgets.Select(attrs=attrs, choices=years), widgets.TextInput(attrs=attrs), ) super(MonthSelectorWidget, self).__init__(_widgets, attrs)
def render(self, context, instance, placeholder): context = super(BirthdayCalendarPlugin, self).render(context, instance, placeholder) User = get_user_model() # Extracts/Truncates are only avaible in Django 1.10+ users = list(User.objects.filter(birthdate__isnull=False)) users.sort(key=lambda u: (u.birthdate.month, u.birthdate.day)) context['profiles'] = users context['months'] = [m[1] for m in sorted(MONTHS.items())] return context
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] output = [] if "id" in self.attrs: id_ = self.attrs["id"] else: id_ = "id_%s" % name month_choices = MONTHS.items() if not (self.required and value): month_choices.append(self.none_value_month) month_choices.sort() local_attrs = self.build_attrs(id=self.month_field % id_) s = Select(choices=month_choices) if self.attrs_month is not None: local_attrs.update({"class": self.attrs_month}) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) day_choices = [(i, i) for i in range(1, 32)] if not (self.required and value): day_choices.insert(0, self.none_value_day) local_attrs["id"] = self.day_field % id_ if self.attrs_day is not None: local_attrs.update({"class": self.attrs_day}) s = Select(choices=day_choices) select_html = s.render(self.day_field % name, day_val, local_attrs) output.append(select_html) year_choices = [(i, i) for i in self.years] if not (self.required and value): year_choices.insert(0, self.none_value_year) local_attrs["id"] = self.year_field % id_ if self.attrs_year is not None: local_attrs.update({"class": self.attrs_year}) s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(select_html) return mark_safe(u"\n".join(output))
def __init__(self, attrs=None): current_year = date.today().year years = reversed([(current_year + i, current_year + i) for i in range(-2, 2)]) months = MONTHS.items() _widgets = ( widgets.HiddenInput(attrs=attrs), widgets.Select(attrs=attrs, choices=months), widgets.Select(attrs=attrs, choices=years), ) super(self.__class__, self).__init__(_widgets, attrs)
def __init__(self, *args, **kwargs): DAYS_CHOICES = [('','-------')] + [(y,y) for y in range(1,32)] MONTHS_CHOICES = [('','-------')] + MONTHS.items() year = date.today().year YEARS_CHOICES = [('','-------')] + [(y,y) for y in range(year-1, year+50)] widgets = [ forms.Select(choices=DAYS_CHOICES), forms.Select(choices=MONTHS_CHOICES), forms.Select(choices=YEARS_CHOICES), ] super(YearMonthWidget, self).__init__(widgets=widgets, *args, **kwargs)
def as_dict(self): widget_dict = super(RemoteSelectDateWidget, self).as_dict() widget_dict['input_type'] = 'selectdatewidget' current_year = datetime.datetime.now().year widget_dict['choices'] = [{ '%s_day' % self.field_name: [{'key': x, 'value': x} for x in range(1, 32)], '%s_month' % self.field_name: [{'key': x, 'value': y} for (x, y) in MONTHS.items()], '%s_year' % self.field_name: [{'key': x, 'value': x} for x in range(current_year - 100, current_year + 1)] }] return widget_dict
def as_dict(self): widget_dict = super(RemoteDateInput, self).as_dict() widget_dict["input_type"] = "date" current_year = datetime.datetime.now().year widget_dict["choices"] = [ {"title": "day", "data": [{"key": x, "value": x} for x in range(1, 32)]}, {"title": "month", "data": [{"key": x, "value": y} for (x, y) in MONTHS.items()]}, {"title": "year", "data": [{"key": x, "value": x} for x in range(current_year - 100, current_year + 1)]}, ] return widget_dict
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): parts = value.split('-', 2) count = len(parts) if count < 3: parts[count:2] = [None] * 3 - count year_val, month_val, day_val = parts output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name def add_class(attrs, className): if 'class' in attrs: attrs['class'] += ' %s' % className else: attrs['class'] = className return attrs # TODO: add fields order customization month_choices = MONTHS.items() if not (self.required and value): month_choices.append(self.none_value) month_choices.sort() local_attrs = self.build_attrs(id=self.month_field % id_) add_class(local_attrs, 'DateMonth') s = widgets.Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) local_attrs = self.build_attrs(id=self.day_field % id_) add_class(local_attrs, 'DateDay') s = widgets.TextInput() select_html = s.render(self.day_field % name, day_val, local_attrs) output.append(select_html) local_attrs = self.build_attrs(id=self.year_field % id_) add_class(local_attrs, 'DateYear') s = widgets.TextInput() select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(select_html) return mark_safe(u'\n'.join(output))
def render(self, name, value, attrs=None, extra_context={}): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, six.text_type): if settings.USE_L10N: try: input_format = formats.get_format( 'DATE_INPUT_FORMATS' )[0] v = datetime.datetime.strptime(value, input_format) year_val, month_val, day_val = v.year, v.month, v.day except ValueError: pass else: match = RE_DATE.match(value) if match: year_val, month_val, day_val = map(int, match.groups()) context = self.get_context(name, value, attrs=attrs, extra_context=extra_context) context['year_choices'] = [(i, i) for i in self.years] context['year_val'] = year_val context['month_choices'] = list(MONTHS.items()) context['month_val'] = month_val context['day_choices'] = [(i, i) for i in range(1, 32)] context['day_val'] = day_val # Theoretically the widget should use self.is_required to determine # whether the field is required. For some reason this widget gets a # required parameter. The Django behaviour is preferred in this # implementation. # Django also adds none_value only if there is no value. The choice # here is to treat the Django behaviour as a bug: if the value isn't # required, then it can be unset. if self.required is False: context['year_choices'].insert(0, self.none_value) context['month_choices'].insert(0, self.none_value) context['day_choices'].insert(0, self.none_value) if callable(self.template_name): template_name = self.template_name(context, self) else: template_name = self.template_name return loader.render_to_string(template_name, context)
def __init__(self, attrs=None): months = [('', '--')] + MONTHS.items() cur_year = datetime.date.today().year year_to_add = datetime.date.today().year years_to_display = [] while year_to_add > cur_year - 50: years_to_display.append((year_to_add, year_to_add)) year_to_add = year_to_add - 1; years_to_display = [('', '----')] + years_to_display _widgets = ( forms.widgets.Select(attrs=attrs, choices=months), forms.widgets.Select(attrs=attrs, choices=years_to_display), ) super(DateYearMonthWidget, self).__init__(_widgets, attrs)
def render(self, name, value, attrs=None, extra_context={}): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, six.text_type): if settings.USE_L10N: try: input_format = formats.get_format( 'DATE_INPUT_FORMATS')[0] v = datetime.datetime.strptime(value, input_format) year_val, month_val, day_val = v.year, v.month, v.day except ValueError: pass else: match = RE_DATE.match(value) if match: year_val, month_val, day_val = map(int, match.groups()) context = self.get_context(name, value, attrs=attrs, extra_context=extra_context) context['year_choices'] = [(i, i) for i in self.years] context['year_val'] = year_val context['month_choices'] = list(MONTHS.items()) context['month_val'] = month_val context['day_choices'] = [(i, i) for i in range(1, 32)] context['day_val'] = day_val # Theoretically the widget should use self.is_required to determine # whether the field is required. For some reason this widget gets a # required parameter. The Django behaviour is preferred in this # implementation. # Django also adds none_value only if there is no value. The choice # here is to treat the Django behaviour as a bug: if the value isn't # required, then it can be unset. if self.required is False: context['year_choices'].insert(0, self.none_value) context['month_choices'].insert(0, self.none_value) context['day_choices'].insert(0, self.none_value) return loader.render_to_string(self.template_name, context)
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [ int(v) for v in match.groups() ] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name day_choices = [(i, i) for i in range(1, 32)] if not (self.required and value): day_choices.insert(0, self.none_value) local_attrs = self.build_attrs(id=self.day_field % id_) s = Select(choices=day_choices) select_html = s.render(self.day_field % name, day_val, local_attrs) output.append(select_html) month_choices = MONTHS.items() if not (self.required and value): month_choices.append(self.none_value) month_choices.sort() local_attrs['id'] = self.month_field % id_ s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) year_choices = [(i, i) for i in self.years] if not (self.required and value): year_choices.insert(0, self.none_value) local_attrs['id'] = self.year_field % id_ s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(select_html) return mark_safe(u'\n'.join(output))
def pull(request): if request.method == "POST": date = "{year}{month}{day}".format(year=request.POST.get('year'), month=request.POST.get('month'), day=request.POST.get('day')) return HttpResponseRedirect(reverse('attendance:select_by_date', args=(date,))) months = [] for month_num, month in MONTHS.items(): months.append(("%02d" % month_num, month)) days = [x for x in range(1, 32)] days = ["%02d" % x for x in days] c = { "months": months, "days": days, "action_active": 'active', } return render(request, "attendance/pull.html", c)
def render(self, name, value, attrs=None): try: year_val, month_val = map(int, value.split('-')) except (AttributeError, TypeError, ValueError): year_val = month_val = None output = [] month_choices = MONTHS.items() month_choices.sort() select_html = Select(choices=month_choices).render(self.month_field % name, month_val, attrs = attrs) output.append(select_html) year_choices = [(i, i) for i in self.years] select_html = Select(choices=year_choices).render(self.year_field % name, year_val, attrs = attrs) output.append(select_html) return u'\n'.join(output)
class Month(Model): name = CharField(max_length=50, unique=True, verbose_name=_('Name')) value = IntegerField(choices=MONTHS.items()) update_time = DateTimeField(auto_now=True, auto_now_add=False, null=True, blank=True, verbose_name=_('Updated')) class Meta: verbose_name = _('Month') verbose_name_plural = _('Month') def __str__(self): return str(self.name) def __unicode__(self): return str(self.name)
class GraduadoForm(forms.Form): plancarrera = forms.CharField(widget=forms.HiddenInput) month = forms.ChoiceField(choices=MONTHS.items(), label=_('Month')) year = forms.ChoiceField(label=_('Year'), choices=[ (i, i) for i in range(date.today().year, 1940, -1) ]) graduado_date = forms.CharField(widget=forms.HiddenInput, required=False) def clean_graduado_date(self): if 'month' not in self.cleaned_data or \ 'year' not in self.cleaned_data: raise forms.ValidationError( _('La fecha de egreso de FIUBA es obligatoria')) month = int(self.cleaned_data['month']) year = int(self.cleaned_data['year']) return date(year, month, 1)
def as_dict(self): widget_dict = super(RemoteDateInput, self).as_dict() widget_dict['input_type'] = 'date' current_year = datetime.datetime.now().year widget_dict['choices'] = [{ 'title': 'day', 'data': [{'key': x, 'value': x} for x in range(1, 32)] }, { 'title': 'month', 'data': [{'key': x, 'value': y} for (x, y) in MONTHS.items()] }, { 'title': 'year', 'data': [{'key': x, 'value': x} for x in range(current_year - 100, current_year + 1)] }] return widget_dict
def __init__(self, attrs=None, end=False, required=False): self.attrs = attrs or {} self.required = required self.today = datetime.date.today() self.round_to_end = end # Years this_year = self.today.year self.year_choices = [(i, i) for i in range(this_year - 4, this_year + 1)] if not self.required: self.year_choices.insert(0, self.none_value) # Month self.month_choices = dict(MONTHS.items()) if not self.required: self.month_choices[self.none_value[0]] = self.none_value[1] self.month_choices = sorted(self.month_choices.items())
def render(self, name, value, attrs=None, renderer=None): try: year_val, month_val, day_val = value.get_year(), value.get_month( empty_allowed=True), value.get_day(empty_allowed=True) except AttributeError: year_val, month_val, day_val = None, None, None output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name local_attrs = self.build_attrs(id=self.year_field % id_) year_choices = [(i, i) for i in self.years] year_choices.reverse() if not self.required: year_choices = [(0, '(year)')] + year_choices s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs, renderer) output.append(select_html) month_choices = list(MONTHS.items()) month_choices.append(self.none_value) month_choices.sort() local_attrs['id'] = self.month_field % id_ s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs, renderer) output.append(select_html) day_choices = [(i, i) for i in range(1, 32)] day_choices.insert(0, self.none_value) local_attrs['id'] = self.day_field % id_ s = Select(choices=day_choices) select_html = s.render(self.day_field % name, day_val, local_attrs, renderer) output.append(select_html) return mark_safe(u'\n'.join(output))
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): if settings.USE_L10N: try: input_format = get_format('DATE_INPUT_FORMATS')[0] # Python 2.4 compatibility: # v = datetime.datetime.strptime(value, input_format) # would be clearer, but datetime.strptime was added in # Python 2.5 v = datetime.datetime(*(time.strptime(value, input_format)[0:6])) year_val, month_val, day_val = v.year, v.month, v.day except ValueError: pass else: match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] choices = [(i, i) for i in self.years] year_html = self.create_select(name, self.year_field, value, year_val, choices) choices = MONTHS.items() month_html = self.create_select(name, self.month_field, value, month_val, choices) choices = [(i, i) for i in range(1, 32)] day_html = self.create_select(name, self.day_field, value, day_val, choices) format = get_format('DATE_FORMAT') escaped = False output = [] for char in format: if escaped: escaped = False elif char == '\\': escaped = True elif char in 'Yy': output.append(year_html) elif char in 'bFMmNn': output.append(month_html) elif char in 'dj': output.append(day_html) return mark_safe(u'\n'.join(output))
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): if settings.USE_L10N: try: input_format = get_format('DATE_INPUT_FORMATS')[0] # Python 2.4 compatibility: # v = datetime.datetime.strptime(value, input_format) # would be clearer, but datetime.strptime was added in # Python 2.5 v = datetime.datetime( *(time.strptime(value, input_format)[0:6])) year_val, month_val, day_val = v.year, v.month, v.day except ValueError: pass else: match = RE_DATE.match(value) if match: year_val, month_val, day_val = [ int(v) for v in match.groups() ] choices = [(i, i) for i in self.years] year_html = self.create_select(name, self.year_field, value, year_val, choices) choices = MONTHS.items() month_html = self.create_select(name, self.month_field, value, month_val, choices) choices = [(i, i) for i in range(1, 32)] day_html = self.create_select(name, self.day_field, value, day_val, choices) output = [] for field in _parse_date_fmt(): if field == 'year': output.append(year_html) elif field == 'month': output.append(month_html) elif field == 'day': output.append(day_html) return mark_safe(u'\n'.join(output))
def render(self, name, value, attrs=None): if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime): value = datetime.datetime(value.year, value.month, value.day) if not value: value = self.default elif type(value) in ('str', 'unicode'): try: value = datetime.datetime.strptime(value, '%Y-%m-%d %H:%M') except: value = self.default year_val, month_val, day_val, hour_val, minute_val = value.year, value.month, value.day, value.hour, value.minute output = [] month_choices = MONTHS.items() month_choices.sort() select_html = Select(choices=month_choices).render(self.month_field % name, month_val) output.append(select_html) day_choices = [(i, i) for i in range(1, 32)] select_html = Select(choices=day_choices, attrs={'style':'width: 50px'}).render(self.day_field % name, day_val) output.append(select_html) year_choices = [(i, i) for i in self.years] select_html = Select(choices=year_choices, attrs={'style':'width: 70px'}).render(self.year_field % name, year_val) output.append(select_html) if self.show_time: html = Input(attrs={'size':5}).render(self.hour_field % name, hour_val) output.append(' ' + html) html = Input(attrs={'size':5}).render(self.minute_field % name, minute_val) output.append(html) null_field = None if self.null: null_field = CheckboxInput(attrs={'id': self.null_field % name}).render(self.null_field % name, self.is_null) t = loader.get_template(self.template) return t.render(Context({ 'select_field': mark_safe(u'\n'.join(output)), 'null_field': null_field, 'name': name, }))
def render(self, name, value, attrs=None): try: year_val, month_val = value.year, value.month except AttributeError: year_val = month_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [ int(v) for v in match.groups() ] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name month_choices = MONTHS.items() if not (self.required and value): month_choices.append(self.none_value) month_choices.sort() build_attrs = {'id': self.month_field % id_} local_attrs = self.build_attrs(build_attrs) s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) year_choices = [(i, i) for i in self.years] if not (self.required and value): year_choices.insert(0, self.none_value) local_attrs['id'] = self.year_field % id_ s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(select_html) # Hidden widget for custom datefield s = HiddenInput() output.append(s.render('date_mozillian', None)) return mark_safe(u'\n'.join(output))
def render(self, name, value, attrs=None): try: year_val, month_val = value.year, value.month except AttributeError: year_val = month_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name month_choices = MONTHS.items() if not (self.required and value): month_choices.append(self.none_value) month_choices.sort() build_attrs = { 'id': self.month_field % id_ } local_attrs = self.build_attrs(build_attrs) s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) year_choices = [(i, i) for i in self.years] if not (self.required and value): year_choices.insert(0, self.none_value) local_attrs['id'] = self.year_field % id_ s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(select_html) # Hidden widget for custom datefield s = HiddenInput() output.append(s.render('date_mozillian', None)) return mark_safe(u'\n'.join(output))
class Rent(models.Model): PAYMENT = (('M-PESA', 'M-PESA'), ('BANK', 'BANK'), ('CASH', 'CASH')) choices = [(k, v) for k, v in MONTHS.items()] month = models.IntegerField(choices=choices, blank=True, null=True, default=datetime.datetime.now().month) date_paid = models.DateField(("Date"), default=date.today, null=True, blank=True) unit = models.ForeignKey(Unit, on_delete=models.CASCADE, null=True, related_name='unit_rent') Amount_paid = models.FloatField() Balance = models.FloatField(null=True) mode_of_payment = models.CharField(max_length=50, choices=PAYMENT, null=True) Reciept_no = models.CharField(max_length=300, blank=True, null=True) paid = models.BooleanField(default=True) service_charge = models.FloatField(default=0) YEAR_CHOICES = [] for r in range(1980, (datetime.datetime.now().year + 20)): YEAR_CHOICES.append((r, r)) year = models.IntegerField(choices=YEAR_CHOICES, default=datetime.datetime.now().year, null=True, blank=True) def Balance(self): if self.Amount_paid < self.unit.monthly_rent: self.Balance = self.unit.monthly_rent - self.Amount_paid else: self.Balance = 0 return self.Balance def __str__(self): return 'ksh. {}'.format(self.Amount_paid)
def render(self, name, value, attrs=None, renderer=None): try: year_val, month_val = value.year, value.month except AttributeError: year_val = month_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [ int(v) for v in match.groups() ] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name month_choices = MONTHS.items() # if not (self.required and value): #MONTHS[0] = self.month_none_value[1] # month_choices.append(self.none_value) #month_choices = MONTHS.items() month_choices = sorted(month_choices) #myfield = self.month_field % id_ # , extra_attrs={id: myfield} local_attrs = self.build_attrs(base_attrs={}) local_attrs['id'] = self.month_field % id_ s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) year_choices = [(i, i) for i in self.years] # if not (self.required and value): # year_choices.insert(0, self.year_none_value) local_attrs['id'] = self.year_field % id_ s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(select_html) return mark_safe(u'\n'.join(output))
def __init__(self, attrs=None, days=None, months=None, years=None): # years is an optional list/tuple of years to use in the "year" select box. self.attrs = attrs or {} if days: self.months = days else: self.days = range(1, 32) if months: self.months = months else: self.months = MONTHS.items() self.months.sort() if years: self.years = years else: this_year = datetime.date.today().year self.years = range(this_year, this_year + 10)
def __init__(self, attrs=None, days=None, months=None, years=None): # years is an optional list/tuple of years to use in the "year" select box. self.attrs = attrs or {} if days: self.months = days else: self.days = range(1, 32) if months: self.months = months else: self.months = MONTHS.items() self.months.sort() if years: self.years = years else: this_year = datetime.date.today().year self.years = range(this_year, this_year+10)
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.get_year(), value.get_month(empty_allowed=True), value.get_day(empty_allowed=True) except AttributeError: year_val, month_val, day_val = None, None, None output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name local_attrs = self.build_attrs(id=self.year_field % id_) year_choices = [(i, i) for i in self.years] year_choices.reverse() if not self.required: year_choices = [(0,'(year)')] + year_choices s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(select_html) month_choices = list(MONTHS.items()) month_choices.append(self.none_value) month_choices.sort() local_attrs['id'] = self.month_field % id_ s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) day_choices = [(i, i) for i in range(1, 32)] day_choices.insert(0, self.none_value) local_attrs['id'] = self.day_field % id_ s = Select(choices=day_choices) select_html = s.render(self.day_field % name, day_val, local_attrs) output.append(select_html) return mark_safe(u'\n'.join(output))
def choices(self, changelist): yield { 'selected': self.month() == 0, 'this_year': today.year, 'year': self.year(), 'value': 0, 'query_string': changelist.get_query_string({}, ['month', 'year']), 'label': 'Not set', 'param_month_name': self.param_month_name, 'param_year_name': self.param_year_name, } for num, name in MONTHS.items(): yield { 'selected': num == self.month(), 'this_year': today.year, # this is tricky... 'year': self.year(), # this is tricky... 'value': num, 'query_string': changelist.get_query_string({}, ['month', 'year']), 'label': name, }
class Expense(models.Model): YEAR_CHOICES = [] for r in range(1980, (datetime.datetime.now().year + 20)): YEAR_CHOICES.append((r, r)) year = models.IntegerField(choices=YEAR_CHOICES, default=datetime.datetime.now().year, null=True, blank=True) choices = [(k, v) for k, v in MONTHS.items()] month = models.IntegerField(choices=choices, blank=True, null=True, default=datetime.datetime.now().month) property_code = models.ForeignKey(Property, on_delete=models.CASCADE) Description = models.TextField(max_length=300) Amount = models.FloatField() Date = models.DateField(("Date"), default=date.today) def __str__(self): return '{}'.format(self.Amount)
def render(self, name, value, attrs=None): super().render(name, value, attrs) flat_attrs = flatatt(attrs) context = { 'name': name, 'attrs': flat_attrs, 'id': attrs['id'], 'closeText': _("Close"), 'currentText': _("Today"), 'dayNames': mark_safe(list2str((str(item[1]) for item in WEEKDAYS.items()))), 'dayNamesMin': mark_safe( list2str((str(item[1]) for item in WEEKDAYS_ABBR.items()))), 'dayNamesShort': mark_safe( list2str((str(item[1]) for item in WEEKDAYS_ABBR.items()))), 'firstDay': mark_safe('"' + str(WEEKDAYS[settings.FIRST_DAY_OF_WEEK]) + '"'), 'isRTL': str(get_language_bidi()).lower(), 'monthNames': mark_safe(list2str((str(item[1]) for item in MONTHS.items()))), 'monthNamesShort': mark_safe(list2str((str(item[1]) for item in MONTHS_3.items()))), 'nextText': mark_safe('"' + str(_('Next')) + '"'), 'prevText': mark_safe('"' + str(_('Previous')) + '"'), 'weekHeader': mark_safe('"' + str(_('Wk')) + '"'), } template = get_template('users/datetimepicker.html') return template.render(context)
def _choices(pattern): if pattern == '%b': choices = MONTHS_3.items() choices.sort() elif pattern == '%B': choices = MONTHS.items() choices.sort() elif pattern == '%d': choices = [(i, i) for i in range(1, 32)] elif pattern == '%m': choices = [(i, i) for i in range(1, 13)] elif pattern == '%y': choices = [(i, str(i)[-2:]) for i in self.years] elif pattern == '%Y': choices = [(i, i) for i in self.years] if self.null and not self.null_label: self.null_label = mark_safe('—') if self.null_label: choices.insert(0, (None, self.null_label)) return tuple(choices)
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name month_choices = MONTHS.items() month_choices.sort() month_choices.append(("","Month")) local_attrs = self.build_attrs(id=self.month_field % id_) month_html = Select(choices=month_choices).render(self.month_field % name, month_val, local_attrs) day_choices = [(i, i) for i in range(1, 32)] day_choices.append(('','Day')) local_attrs['id'] = self.day_field % id_ day_html = Select(choices=day_choices).render(self.day_field % name, day_val, local_attrs) year_choices = [(i, i) for i in self.years] year_choices.append(("","Year")) local_attrs['id'] = self.year_field % id_ year_html = Select(choices=year_choices).render(self.year_field % name, year_val, local_attrs) output.append(day_html) output.append(month_html) output.append(year_html) return mark_safe(u'\n'.join(output))
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name month_choices = MONTHS.items() month_choices.sort() local_attrs = self.build_attrs(id=self.month_field % id_) select_html = Select(choices=month_choices).render(self.month_field % name, month_val, local_attrs) output.append(select_html) day_choices = [(i, i) for i in range(1, 32)] local_attrs['id'] = self.day_field % id_ select_html = Select(choices=day_choices).render(self.day_field % name, day_val, local_attrs) output.append(select_html) # if later on they decide that they do want this order swapped then just # uncomment this line # output[0], output[1] = output[1], output[0] year_choices = [(i, i) for i in self.years] local_attrs['id'] = self.year_field % id_ select_html = Select(choices=year_choices).render(self.year_field % name, year_val, local_attrs) output.append(select_html) return mark_safe(u'\n'.join(output))
class StripePaymentForm(CardForm): def __init__(self, *args, **kwargs): super(StripePaymentForm, self).__init__(*args, **kwargs) self.fields['card_cvv'].label = "Card CVC" self.fields[ 'card_cvv'].help_text = "Card Verification Code; see rear of card." months = [(m[0], '%02d - %s' % (m[0], str(m[1]))) for m in sorted(MONTHS.items())] self.fields['card_expiry_month'].choices = months card_number = forms.CharField(required=False, max_length=20, widget=NoNameTextInput()) card_cvv = forms.CharField(required=False, max_length=4, widget=NoNameTextInput()) card_expiry_month = forms.ChoiceField(required=False, widget=NoNameSelect(), choices=iter(MONTHS.items())) card_expiry_year = forms.ChoiceField( required=False, widget=NoNameSelect(), choices=options.ZEBRA_CARD_YEARS_CHOICES)
def render(self, name, value, attrs=None): try: value = datetime.date(*map(int, value.split('-'))) year_val, month_val, day_val = value.year, value.month, value.day except (AttributeError, TypeError, ValueError): year_val = month_val = day_val = None output = [] month_choices = MONTHS.items() month_choices.sort() select_html = Select(choices=month_choices).render(self.month_field % name, month_val) output.append(select_html) day_choices = [(i, i) for i in range(1, 32)] select_html = Select(choices=day_choices).render(self.day_field % name, day_val) output.append(select_html) year_choices = [(i, i) for i in self.years] select_html = Select(choices=year_choices).render(self.year_field % name, year_val) output.append(select_html) return u'\n'.join(output)
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [ int(v) for v in match.groups() ] choices = [(i, i) for i in self.years] year_html = self.create_select(name, self.year_field, value, year_val, choices) choices = MONTHS.items() month_html = self.create_select(name, self.month_field, value, month_val, choices) choices = [(i, i) for i in range(1, 32)] day_html = self.create_select(name, self.day_field, value, day_val, choices) format = get_format('DATE_FORMAT') escaped = False output = [] for char in format: if escaped: escaped = False elif char == '\\': escaped = True elif char in 'Yy': output.append(year_html) elif char in 'bFMmNn': output.append(month_html) elif char in 'dj': output.append(day_html) return mark_safe(u'\n'.join(output))
def render(self, name, value, attrs=None): try: year_val, month_val = value.year, value.month except AttributeError: year_val = month_val = None if isinstance(value, str): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [ int(v) for v in match.groups() ] output = [] if "id" in self.attrs: id_ = self.attrs["id"] else: id_ = "id_%s" % name month_choices = MONTHS.items() if not (self.required and value): month_choices.append(self.none_value) month_choices.sort() local_attrs = self.build_attrs(id=self.month_field % id_) s = forms.Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) year_choices = [(i, i) for i in self.years] if not (self.required and value): year_choices.insert(0, self.none_value) local_attrs["id"] = self.year_field % id_ s = forms.Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(select_html) return mark_safe("\n".join(output))
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, str): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name year_choices = [(0, 'YYYY'), ] + [(i, i) for i in reversed(self.years)] local_attrs = self.build_attrs({"id": self.year_field % id_, "class": "select"}) s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append('<div class="col-xl-8">%s</div>' % select_html) month_choices = [(0, 'MM'), ] + list(MONTHS.items()) local_attrs['id'] = self.month_field % id_ s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append('<div class="col-xl-8">%s</div>' % select_html) day_choices = [(0, 'DD'), ] + [(i, i) for i in range(1, 32)] local_attrs['id'] = self.day_field % id_ s = Select(choices=day_choices) select_html = s.render(self.day_field % name, day_val, local_attrs) output.append('<div class="col-xl-8">%s</div>' % select_html) return mark_safe(u'\n'.join(output))
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] output = [] if "id" in self.attrs: id_ = self.attrs["id"] else: id_ = "id_%s" % name day_choices = [(i, i) for i in range(1, 32)] local_attrs = self.build_attrs(id=self.day_field % id_) select_html = Select(choices=day_choices).render(self.day_field % name, day_val, local_attrs) output.append(select_html) month_choices = MONTHS.items() month_choices.sort() local_attrs["id"] = self.month_field % id_ select_html = Select(choices=month_choices).render(self.month_field % name, month_val, local_attrs) output.append(select_html) year_choices = [(i, i) for i in self.years] local_attrs["id"] = self.year_field % id_ if self.reverse_years: year_choices.reverse() select_html = Select(choices=year_choices).render(self.year_field % name, year_val, local_attrs) output.append(select_html) return mark_safe(u"\n".join(output))
def get_date_filter_choices(): today = datetime.date.today() empty = [(0, '---')] months = empty + list(MONTHS.items()) years = empty + [(i, i) for i in range(today.year - 4, today.year + 1)] return months, years
from datetime import datetime from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.dates import MONTHS from utils.uploads import get_unique_upload_path from .utils import generate_thumbnail MONTH_CHOICES = [(key, value) for key, value in MONTHS.items()] YEAR_CHOICES = [(year, year) for year in range(1950, (datetime.now().year + 1))] class Location(models.Model): """A location is a physical location that can be applied to an album.""" name = models.CharField(_('name'), max_length=200) class Meta: ordering = ['name', ] verbose_name = _('location') verbose_name_plural = _('locations') @models.permalink def get_absolute_url(self): return ('location', [str(self.id)]) def __str__(self): return self.name
class PaymentAdvForm(forms.Form): value = forms.IntegerField(label="Kwota", min_value=0, max_value=10000, help_text='*') info = forms.CharField( label="Wpisz info", required=False, widget=forms.Textarea(), max_length=64, ) month_choices = MONTHS.items() class SetMonthForm(forms.Form): month = forms.ChoiceField(choices=month_choices, label="Miesiąc", initial=datetime.now().month, widget=forms.Select(), help_text="*", required=False) CHOICES = ( (0, 'Wszystko'), (1, 'Wypłata'), (2, 'Zaliczka'),
class UserSignupForm(forms.Form): invitation_code = forms.CharField(max_length=30, label=_("Invitation Code"), help_text=_("While in pilot mode, " "an invitation code " "is needed to register.") ) id_number = forms.CharField(max_length=9, label=_("Medicare Number"), help_text=_("The 9 digit number on your Medicare card." "Do not provide dashes or spaces. We use this to lookup your medical records.") ) id_suffix = forms.ChoiceField(choices=MEDICARE_SUFFIX_CHOICES, help_text=_("The code following your Medicare " "number on your Medicare card.")) effective_date_month = forms.ChoiceField(choices=MONTHS.items(), help_text=_("Effective Month for Part A. " "This information can be found on your Medicare card.")) effective_date_year = forms.CharField(max_length=4, help_text=_("Effective Month for Part A. " "This information can be found on your Medicare card.")) username = forms.CharField(max_length=30, label=_("User"), help_text=_("Choose your desired user name.")) email = forms.EmailField(max_length=75, label=_("Email")) first_name = forms.CharField(max_length=100, label=_("First Name")) last_name = forms.CharField(max_length=100, label=_("Last Name")) mobile_phone_number = USPhoneNumberField(required=False, label=_("Mobile Phone Number " "(Optional)"), help_text=_("We use this for " "multi-factor " "authentication. " "US numbers only.")) password1 = forms.CharField(widget=forms.PasswordInput, max_length=120, label=_("Password")) password2 = forms.CharField(widget=forms.PasswordInput, max_length=120, label=_("Password (again)")) this_is_me_or_agent = forms.CharField(widget=forms.CheckboxInput, label=_(""), required=True, help_text="I attest the above information is about me " "or I have been given permission by the person listed " "to create this account on her or his account. For example," "the person above is one of your parents.") primary_care_first_name = forms.CharField(max_length=100, label=_("Primary Care Physician First Name")) primary_care_last_name = forms.CharField(max_length=100, label=_("Primary Care Physician Last Name")) human_x = randint(1, 9) human_y = randint(1, 9) human_z = human_x + human_y human_q = ('What is %s + %s?' % (human_x, human_y)) human = forms.CharField( max_length=2, label=_(human_q), help_text='We are asking this to make sure you are human. ' 'Hint: the answer is %s.' % human_z, ) required_css_class = 'required' def clean_human(self): human = self.cleaned_data.get('human', '') logger.debug("Compare [%s] to [%s]" % (str(human), str(self.human_z))) if str(human) != str(self.human_z): raise forms.ValidationError(_('You are either not human or ' 'just just really bad at math.')) return human def clean_password2(self): password1 = self.cleaned_data.get("password1", "") password2 = self.cleaned_data["password2"] if password1 != password2: raise forms.ValidationError( _("The two password fields didn't match.")) try: validate_password(password1) except ValidationError as err: raise forms.ValidationError(err.error_list[0]) return password2 def clean_email(self): email = self.cleaned_data.get('email', "") if email: username = self.cleaned_data.get('username') if email and User.objects.filter(email=email).exclude( username=username).count(): raise forms.ValidationError( _('This email address is already registered.')) return email.rstrip().lstrip().lower() else: return email.rstrip().lstrip().lower() def clean_username(self): username = self.cleaned_data.get('username') username = username.rstrip().lstrip().lower() if User.objects.filter(username=username).count() > 0: raise forms.ValidationError(_('This username is already taken.')) return username def clean_invitation_code(self): invitation_code = self.cleaned_data['invitation_code'] if UserRegisterCode.objects.filter(used=False, code=invitation_code).count() != 1: raise forms.ValidationError(_('The invitation code is not valid.')) return invitation_code def save(self): invitation_code = self.cleaned_data['invitation_code'] # make the invitation a invalid/spent. invite = UserRegisterCode.objects.get( code=str(invitation_code), used=False) invite.valid = False invite.save() new_user = User.objects.create_user( username=self.cleaned_data['username'], first_name=self.cleaned_data['first_name'], last_name=self.cleaned_data['last_name'], password=self.cleaned_data['password1'], email=self.cleaned_data['email'], is_active=False) UserProfile.objects.create(user=new_user, organization_name=self.cleaned_data[ 'organization_name'], user_type="DEV", create_applications=True, password_reset_question_1=self.cleaned_data[ 'password_reset_question_1'], password_reset_answer_1=self.cleaned_data[ 'password_reset_answer_1'], password_reset_question_2=self.cleaned_data[ 'password_reset_question_2'], password_reset_answer_2=self.cleaned_data[ 'password_reset_answer_2'], password_reset_question_3=self.cleaned_data[ 'password_reset_question_3'], password_reset_answer_3=self.cleaned_data[ 'password_reset_answer_3'] ) group = Group.objects.get(name='BlueButton') new_user.groups.add(group) # Send a verification email create_activation_key(new_user) return new_user
def month_summary(request, month, year): if request.method == "POST": month = request.POST.get("month_selector", month) year = request.POST.get("year_selector", year) return HttpResponseRedirect( reverse('attn:month_summary', args=(month, year))) month_num = month_string_to_number(month) object_list = Attendance.objects.filter(punch__month=month_num, punch__year=int(year)) month_name = calendar.month_name[month_num] cal = calendar.Calendar() dates = [] for date in cal.itermonthdays(int(year), int(month_num)): dates.append(date) while 0 in dates: dates.remove(0) month_days = len(dates) employee_list = Profile.objects.values_list('proximity_id', flat=True) rows = [] for employee in employee_list: rows.append([employee, dates[:], []]) for row in rows: employee_id = row[0] row_objs = object_list.filter(employee_id=employee_id) days = {} late_count = 0 present_count = 0 for obj in row_objs: if obj.punch.day in days: existing_punch = days[obj.punch.day] if len(existing_punch) == 2: raise ValueError( 'More than two values in a punch tuple is not allowed! {} {}' .format(employee_id, obj.punch.date())) existing_punch += (obj.punch.time().strftime("%H:%M"), ) days[obj.punch.day] = existing_punch else: days[obj.punch.day] = (obj.punch.time().strftime("%H:%M"), ) date_count = [] for obj in row_objs: if obj.punch.day not in date_count: if obj.punch.time() > time(9, 30): late_count += 1 else: present_count += 1 date_count.append(obj.punch.day) row[1] = [days.get(x, ('ABS', 'ABS')) for x in row[1]] absent_count = month_days - present_count - late_count row[2] = [present_count, late_count, absent_count] months = [] for month_num, month in MONTHS.items(): months.append(month) c = { "rows": rows, "dates": dates, "month_name": month_name, "object_list": object_list, "year": year, "months": months, } return render(request, "attn/month_summary.html", c)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) family_choices = [(family['id'], family['name']) for family in Family.objects.values('id', 'name')] garden_name_choices = [ (garden['name'], garden['name']) for garden in GardenArea.objects.values('name').distinct('name') ] habit_choices = [(species['habit'], species['habit']) for species in Species.objects.order_by( 'habit').values('habit').distinct('habit')] exposure_choices = [ (species['exposure'], species['exposure']) for species in Species.objects.order_by('exposure').values( 'exposure').distinct('exposure') if species['exposure'] is not '' and species['exposure'] is not None ] water_need_choices = [ (species['water_regime'], species['water_regime']) for species in Species.objects.order_by('water_regime').values( 'water_regime').distinct('water_regime') ] bloom_month_choices = [(v, v) for _, v in MONTHS.items()] # Flower color list of lists flower_colors_split = [ species['flower_color'].split(',') for species in Species.objects.order_by('flower_color').values( 'flower_color').distinct('flower_color') if species['flower_color'] is not '' and species['flower_color'] is not None ] flower_colors_split = [(color.strip(), color.strip()) for colors in flower_colors_split for color in colors] # Flattens list of lists flower_color_choices = sorted( list(OrderedDict.fromkeys( flower_colors_split))) # Removes duplicates commemoration_people_choices = [ (collection['commemoration_person'], collection['commemoration_person']) for collection in Collection.objects.order_by( 'commemoration_person').values( 'commemoration_person').distinct('commemoration_person') if collection['commemoration_person'] is not '' and collection['commemoration_person'] is not None ] # Insert empty choice to lists that don't already have an empty option family_choices.insert(0, (None, '')) garden_name_choices.insert(0, (None, '')) habit_choices.insert(0, (None, '')) exposure_choices.insert(0, (None, '')) water_need_choices.insert(0, (None, '')) bloom_month_choices.insert(0, (None, '')) flower_color_choices.insert(0, (None, '')) commemoration_people_choices.insert(0, (None, '')) self.fields['family_name'].choices = family_choices self.fields['garden_name'].choices = garden_name_choices self.fields['habits'].choices = habit_choices self.fields['exposures'].choices = exposure_choices self.fields['water_needs'].choices = water_need_choices self.fields['bloom_months'].choices = bloom_month_choices self.fields['flower_colors'].choices = flower_color_choices self.fields['memorial_person'].choices = commemoration_people_choices for visible in self.visible_fields(): if isinstance(visible.field.widget, CheckboxInput): pass else: visible.field.widget.attrs['class'] = 'form-control'