Esempio n. 1
0
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 __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for f in ['month', 'year']:
            self.fields[f].widget.attrs.update({'class': 'form-control'})
        self.fields['graduado_date']\
            .widget.attrs.update({'class': 'form-control'})

    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)
Esempio n. 2
0
    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))
Esempio n. 3
0
    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))
Esempio n. 4
0
    def render(self, context, instance, placeholder):
        # # check if we can reverse list view for configured namespace
        # # if no prepare a message to admin users.
        namespace = instance.app_config_id and instance.app_config.namespace
        if not is_valid_namespace(namespace):
            # add message, should be properly handled in template
            context['plugin_configuration_error'] = NO_APPHOOK_ERROR_MESSAGE
            return context

        year = context.get('event_year')
        month = context.get('event_month')

        if not all([year, month]):
            year = str(timezone.now().date().year)
            month = str(timezone.now().date().month)

        current_date = datetime.date(int(year), int(month), 1)
        language = instance.language

        context['event_year'] = year
        context['event_month'] = month
        context['days'] = build_calendar(year, month, language, namespace)
        context['current_date'] = current_date
        context['last_month'] = current_date + datetime.timedelta(days=-1)
        context['next_month'] = current_date + datetime.timedelta(days=35)
        context['calendar_label'] = u'%s %s' % (MONTHS.get(int(month)), year)
        context['calendar_namespace'] = namespace
        context['calendar_language'] = language
        return context
Esempio n. 5
0
    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
Esempio n. 6
0
	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))
Esempio n. 7
0
 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], unicode(m[1])))
                 for m in sorted(MONTHS.iteritems()) ]
     self.fields['card_expiry_month'].choices = months
Esempio n. 8
0
class ReportForm(forms.Form):
    report_month = forms.TypedChoiceField(label='Report Month', required=False,
        coerce=int, choices=MONTHS.items(), 
    )
    report_year = forms.IntegerField(label='Report Year', required=False,
        min_value=1970, max_value=datetime.date.today().year
    )
Esempio n. 9
0
    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()
        local_attrs = self.build_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))
Esempio n. 10
0
def article_list(request, article_category='news'):

    article_category = get_object_or_404(ArticleCategory,
                                         permalink=article_category)

    year_min = News.objects.all().aggregate(Min('created'))['created__min']
    year_min = (year_min and year_min.year) or datetime.date.today().year

    year_list = range(year_min, datetime.date.today().year + 1)

    year_list = [{'title': year, 'permalink': year} for year in year_list]
    month_list = [{
        'permalink': permalink,
        'title': title
    } for permalink, title in MONTHS.iteritems()]

    context = {
        'year_list': year_list,
        'show_year_filter': len(year_list) > 1,
        'month_list': month_list,
        'item_template':
        '<div ng-include="\'template_party_news.html\'"></div>',
        'article_category': article_category,
        'article_category_name': article_category.title  # deprecate
    }

    try:
        return render(request,
                      'cms/news/%s_list.html' % article_category.permalink,
                      context)
    except TemplateDoesNotExist:
        return render(request, 'cms/news/list.html', context)
Esempio n. 11
0
def get_list_entries(request, limit, template_name):
    entry_type = request.GET.get('entry_type', 'all')
    month = int(request.POST.get('month', datetime.date.today().month))
    year = int(request.POST.get('year', datetime.date.today().year))
    incomes = Entry.objects.get_incomes(request.user, month, year, limit)
    expenses = Entry.objects.get_expenses(request.user, month, year, limit)
    all_entries = Entry.objects.get_all_entries(request.user, month, year,
                                                None)
    total_incomes = Entry.objects.get_entries_amount(request.user, incomes)
    total_expenses = Entry.objects.get_entries_amount(request.user, expenses)
    category_amount = Entry.objects.get_amount_expenses_by_category(
        request.user, month, year, None)
    expenses_by_category = get_list_expenses_by_category(
        request, limit, month, year)

    context = {
        'incomes': incomes,
        'expenses': expenses,
        'total_incomes': total_incomes,
        'total_expenses': total_expenses,
        'months': MONTHS.items(),
        'current_month': month,
        'years': get_years(year, 5),
        'current_year': year,
        'all_entries': all_entries,
        'entry_type': entry_type,
        'entries_by_category': expenses_by_category,
        'category_amount': category_amount,
    }

    return render(request, template_name, context)
Esempio n. 12
0
def date_selector(prefix, date=None, disabled=False):
	
	# if no date was provided, select TODAY
	if date == None:
		t = time.localtime()
	
	# if a date was provided (such as a Question.start
	# or .end), extract the values to prepopulate <select>s
	elif isinstance(date, datetime.date):
		t = date.timetuple()
	
	# we have no idea what was passed
	else: raise Exception("wat")
	
	return {
		"prefix": prefix,
		"disabled": disabled,
		
		# for hidden fields
		"year":   t.tm_year,
		"month":  t.tm_mon,
		"day":    t.tm_mday,
		
		# for drop-down selects
		"days":   list((d, d==t.tm_mday) for d in range(1, 32)),
		"months": list((unicode(MONTHS[m]), m==t.tm_mon) for m in MONTHS.iterkeys()),
		"years":  list((y, y==t.tm_year) for y in range(t.tm_year, t.tm_year+5))
	}
Esempio n. 13
0
    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)
Esempio n. 14
0
    def create_projects_parts_and_imputations(self):
        max_projects = 3
        for p in range(0, max_projects):
            project = Project()
            project.internal_id = self.sd.word() + str(p)
            project.name = self.sd.word()
            project.description = self.sd.paragraph()
            project.active = self.sd.boolean()
            project.client = Client.objects.order_by("?")[0]
            project.save()
            project_users = User.objects.order_by("?")[0:3]
            for u in project_users:
                assignation = Assignation(employee=u, project=project)
                assignation.save()

        for u in User.objects.all():
            for year in [2011, 2012, 2013]:
                for month in MONTHS.keys():
                    part = Part()
                    part.month = month
                    part.year = year
                    part.employee = u
                    part.state = self.sd.choice(PART_STATE_CHOICES)[0]
                    part.save()

            for part in u.parts.all():
                part.data = {}
                for project in u.projects.all():
                    project_data = {day+1: self.sd.int(8) for day in range(monthrange(part.year, part.month)[1])}
                    part.data[project.id] = project_data

                part.save()
Esempio n. 15
0
    def render(self, name, value, attrs=None, renderer=None) -> str:
        try:
            year_val, month_val = value.year, value.month
        except AttributeError:
            now = datetime.datetime.now()
            year_val = now.year
            month_val = now.month

        output = []

        if 'id' in self.attrs:
            id_ = self.attrs['id']
        else:
            id_ = f'id_{name}'

        month_choices = list(MONTHS.items())
        if not (self.required and value):
            month_choices.append(self.none_value)
        month_choices.sort()
        local_attrs = self.build_attrs(base_attrs=self.attrs)
        s = Select(choices=month_choices)
        select_html = s.render(self.month_field % name, month_val, local_attrs)
        output.append(select_html)

        local_attrs['id'] = self.year_field % id_
        s = NumberInput()
        select_html = s.render(self.year_field % name, year_val, local_attrs)
        output.append(select_html)

        return mark_safe(u'\n'.join(output))
Esempio n. 16
0
    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)
Esempio n. 17
0
    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_)
        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)]
        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]
        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:
            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)
Esempio n. 19
0
    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))
Esempio n. 20
0
    def render(self, context, instance, placeholder):
        # # check if we can reverse list view for configured namespace
        # # if no prepare a message to admin users.
        namespace = instance.app_config_id and instance.app_config.namespace
        if not namespace_is_apphooked(namespace):
            # add message, should be properly handled in template
            context['plugin_configuration_error'] = NO_APPHOOK_ERROR_MESSAGE
            return context

        year = context.get('event_year')
        month = context.get('event_month')

        if not all([year, month]):
            year = str(timezone.now().date().year)
            month = str(timezone.now().date().month)

        current_date = datetime.date(int(year), int(month), 1)
        language = instance.language

        context['event_year'] = year
        context['event_month'] = month
        context['days'] = build_calendar(year, month, language, namespace)
        context['current_date'] = current_date
        context['last_month'] = current_date + datetime.timedelta(days=-1)
        context['next_month'] = current_date + datetime.timedelta(days=35)
        context['calendar_label'] = u'%s %s' % (MONTHS.get(int(month)), year)
        context['calendar_namespace'] = namespace
        context['calendar_language'] = language
        return context
Esempio n. 21
0
    def render(self, context, instance, placeholder):
        context = super(CalendarPlugin, self).render(context, instance,
                                                     placeholder)
        if context.get('plugin_configuration_error') is not None:
            return context
        namespace = self.get_namespace(instance)
        language = self.get_language(context['request'])
        site_id = getattr(get_current_site(context['request']), 'id', None)
        year = context.get('event_year')
        month = context.get('event_month')

        if not all([year, month]):
            year = str(timezone.now().date().year)
            month = str(timezone.now().date().month)

        current_date = datetime.date(int(year), int(month), 1)

        context['event_year'] = year
        context['event_month'] = month
        context['days'] = build_calendar(year, month, language, namespace,
                                         site_id)
        context['current_date'] = current_date
        context['last_month'] = current_date + datetime.timedelta(days=-1)
        context['next_month'] = current_date + datetime.timedelta(days=35)
        context['calendar_label'] = '%s %s' % (MONTHS.get(int(month)), year)
        context['calendar_namespace'] = namespace
        return context
Esempio n. 22
0
    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))
Esempio n. 23
0
    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))
Esempio n. 24
0
 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], unicode(m[1])))
                 for m in sorted(MONTHS.iteritems()) ]
     self.fields['card_expiry_month'].choices = months
Esempio n. 25
0
    def render(self, context, instance, placeholder):
        context = super(CalendarPlugin, self).render(context, instance,
                                                     placeholder)
        if context.get('plugin_configuration_error') is not None:
            return context
        namespace = self.get_namespace(instance)
        language = self.get_language(context['request'])
        site_id = getattr(get_current_site(context['request']), 'id', None)
        year = context.get('event_year')
        month = context.get('event_month')

        if not all([year, month]):
            year = str(timezone.now().date().year)
            month = str(timezone.now().date().month)

        current_date = datetime.date(int(year), int(month), 1)

        context['event_year'] = year
        context['event_month'] = month
        context['days'] = build_calendar(
            year, month, language, namespace, site_id)
        context['current_date'] = current_date
        context['last_month'] = current_date + datetime.timedelta(days=-1)
        context['next_month'] = current_date + datetime.timedelta(days=35)
        context['calendar_label'] = u'%s %s' % (MONTHS.get(int(month)), year)
        context['calendar_namespace'] = namespace
        return context
Esempio n. 26
0
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], u'%02d - %s' % (m[0], unicode(m[1])))
                  for m in sorted(MONTHS.iteritems())]
        self.fields['card_expiry_month'].choices = months

    card_number = forms.CharField(
        required=False,
        max_length=20,
        widget=NoNameTextInput(attrs={'class': 'span5'}))
    card_cvv = forms.CharField(
        required=False,
        max_length=4,
        widget=NoNameTextInput(attrs={'class': 'span2'}))
    card_expiry_month = forms.ChoiceField(required=False,
                                          widget=NoNameSelect(),
                                          choices=MONTHS.iteritems())
    card_expiry_year = forms.ChoiceField(
        required=False,
        widget=NoNameSelect(),
        choices=options.ZEBRA_CARD_YEARS_CHOICES)
Esempio n. 27
0
    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('\n'.join(output))
Esempio n. 28
0
class Bill(models.Model):
    FACTURA = 'f'
    TICKET = 't'

    BILL_TYPES = (
        (FACTURA, 'Factura'),
        (TICKET, 'Ticket'),
    )
    type = models.CharField(verbose_name='Tipo',
                            max_length=1,
                            db_index=True,
                            choices=BILL_TYPES)

    AGRUPACIONES = 'a'
    DEPORTES = 'd'
    GASTOS_EXC = 'g'

    GIMNASIO = 'o'
    IDIOMAS = 'i'
    INTERNACIONALES = 't'
    LACOPIA = 'l'
    LABORATORIO = 'p'
    NAUTICA = 'n'
    OFICINA = 'f'
    SERVICIOS = 's'

    DEPARTAMENTOS = ((AGRUPACIONES, 'Agrupaciones'), (DEPORTES, 'Deportes'),
                     (GASTOS_EXC, 'Gastos Excepcionales'),
                     (GIMNASIO, 'Gimnasio'), (IDIOMAS, 'Idiomas'),
                     (INTERNACIONALES, 'Internacionales'),
                     (LACOPIA, 'La Copia'), (LABORATORIO, 'Laboratorio'),
                     (NAUTICA, 'Nautica'), (OFICINA, 'Oficina'), (SERVICIOS,
                                                                  'Servicios'))

    departamento = models.CharField(verbose_name='Departamento',
                                    choices=DEPARTAMENTOS,
                                    db_index=True,
                                    max_length=1)

    concepto = models.CharField(verbose_name='Concepto', max_length=300)

    descripcion = models.CharField(verbose_name='Descripcion', max_length=300)

    monto = models.DecimalField(verbose_name='Monto',
                                max_digits=8,
                                decimal_places=2)

    month = models.PositiveSmallIntegerField(verbose_name='Mes',
                                             choices=MONTHS.items(),
                                             db_index=True)

    year = models.PositiveSmallIntegerField(verbose_name='Ano',
                                            default=datetime.date.today().year)

    class Meta:
        verbose_name = 'Factura'
        verbose_name_plural = 'Facturas'
        permissions = (('save_bill',
                        'NEW: Can save changes made to the model'), )
Esempio n. 29
0
def employee_summary(request, employee_id, year):
    attendances = Attendance.objects.filter(punch__year=int(year),
                                            employee_id=employee_id)
    cal = calendar.Calendar()

    dates = []
    for date in range(1, 32):
        dates.append(date)

    attn_year = {}
    summary_dict = {}
    for month_num, month in MONTHS.items():
        attn_year[month_num] = []
        for date in cal.itermonthdays(int(year), int(month_num)):
            attn_year[month_num].append(date)
        while 0 in attn_year[month_num]:
            attn_year[month_num].remove(0)
        month_days = len(attn_year[month_num])

        days = {}
        for attendance in attendances:
            attn_day = attendance.punch.day
            attn_month = attendance.punch.month
            if attn_day in days and attn_month == month_num:
                existing_punch = days[attn_day]
                if len(existing_punch) == 2:
                    raise ValueError(
                        'More than two values in a punch tuple is not allowed! {} {}'
                        .format(employee_id, attendance.punch.date()))
                existing_punch += (attendance.punch.time().strftime("%H:%M"), )
                days[attn_day] = existing_punch
            elif attn_day not in days and attn_month == month_num:
                days[attn_day] = (attendance.punch.time().strftime("%H:%M"), )
        attn_year[month_num] = [
            days.get(x, ('ABS', 'X')) for x in attn_year[month_num]
        ]

        late_count = 0
        present_count = 0
        date_count = []
        for obj in attendances.filter(punch__month=month_num):
            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)
        summary_dict[month_num] = [
            present_count, late_count, month_days - present_count - late_count
        ]

    c = {
        "employee_id": employee_id,
        "year": year,
        "dates": dates,
        "attn_year": attn_year,
        "summary_dict": summary_dict,
    }
    return render(request, "attn/employee_summary.html", c)
Esempio n. 30
0
 def __init__(self, attrs=None):
     # create choices for days, months, years
     _attrs = attrs or {}  # default class
     _attrs['class'] = (_attrs.get('class', '') + ' select').strip()
     _widgets = [widgets.Select(attrs=_attrs, choices=MONTHS.items())]
     _attrs['class'] += " input"
     _widgets.append(widgets.NumberInput(attrs=_attrs))
     super(MonthSelectorWidget, self).__init__(_widgets, attrs)
Esempio n. 31
0
 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)
Esempio n. 32
0
class OffDayFrom(forms.Form):
    from_year = forms.ChoiceField(
        label="Year",
        choices=[(x, x) for x in range(2017, (datetime.now().year + 2))])
    from_month = forms.ChoiceField(label="Month",
                                   choices=[(num, name)
                                            for num, name in MONTHS.items()])
    from_date = forms.ChoiceField(label="Day",
                                  choices=[(x, x) for x in range(1, 32)])
Esempio n. 33
0
class ProductTypeCountsForm(forms.Form):
    month = forms.ChoiceField(choices=MONTHS.items(), required=True, error_messages={
        'required': '*'})
    year = forms.ChoiceField(choices=get_years, required=True, error_messages={
        'required': '*'})
    product_type = forms.ModelChoiceField(required=True,
                                          queryset=Product_Type.objects.all(),
                                          error_messages={
                                              'required': '*'})
Esempio n. 34
0
 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)
Esempio n. 35
0
    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
Esempio n. 36
0
class IssueRequirement(models.Model):
    diary = models.ForeignKey('Diary', on_delete=models.CASCADE, verbose_name='dairy')
    month = models.PositiveSmallIntegerField(choices=MONTHS.items())
    year = models.PositiveSmallIntegerField()
    issue = models.ForeignKey('Issue', on_delete=models.CASCADE)
    requirement = models.DecimalField(max_digits=20, decimal_places=6)

    def __str__(self):
        return str(self.diary.name) + "-" + str(MONTHS[self.month]) + "-" + str(self.year) + "-" + str(
            self.issue.name) + "-" + str(self.requirement)
Esempio n. 37
0
    def __init__(self, attrs=None):
        # create choices for days, months, years
        _widgets = list()
        _attrs = attrs or {}  # default class
        _attrs['class'] = (_attrs.get('class', '') + ' w-month-year').strip()
        _widgets.append(widgets.Select(attrs=_attrs, choices=MONTHS.items()))
        _attrs['class'] += " w-year"
        _widgets.insert(0, widgets.Select(attrs=_attrs, choices=years))

        super(MonthSelectorWidget, self).__init__(_widgets, attrs)
Esempio n. 38
0
class ProcurementGrowthFactor(models.Model):
    month = models.PositiveSmallIntegerField(choices=MONTHS.items())
    year = models.PositiveSmallIntegerField(default=datetime.datetime.now().year)
    growth_factor = models.DecimalField(max_digits=8, decimal_places=4)
    diary = models.ForeignKey('Diary', on_delete=models.CASCADE, verbose_name='dairy')

    class Meta:
        unique_together = ('month', 'diary', 'year',)

    def __str__(self):
        return str(self.year) + "-" + MONTHS[self.month] + "-" + self.diary.name
Esempio n. 39
0
class ActualMonthCategory(models.Model):
    year = models.PositiveSmallIntegerField()
    diary = models.ForeignKey('Diary', on_delete=models.CASCADE)
    month = models.PositiveSmallIntegerField(choices=MONTHS.items())
    category = models.ForeignKey('Category', on_delete=models.CASCADE)
    actual_sale = models.PositiveIntegerField()
    actual_stockin = models.PositiveIntegerField()
    actual_stockout = models.PositiveIntegerField()

    def __str__(self):
        return str(self.year) + "-" + str(self.category.name) + "-" + str(self.month)
Esempio n. 40
0
    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

        # 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())
Esempio n. 41
0
    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)
Esempio n. 42
0
    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))
Esempio n. 43
0
    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)
Esempio n. 44
0
    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
Esempio n. 45
0
    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 list(MONTHS.items())]},
            {"title": "year", "data": [{"key": x, "value": x} for x in range(current_year - 100, current_year + 1)]},
        ]

        return widget_dict
Esempio n. 46
0
    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
Esempio n. 47
0
def build_calendar_context(year, month, language, namespace):
    # if not have a selected date
    today = timezone.now().date()
    if not all([year, month]):
        year = today.year
        month = today.month

    year, month = int(year), int(month)
    current_date = date(year, month, 1)

    if namespace:
        try:
            EventsConfig.objects.get(namespace=namespace)
        except EventsConfig.DoesNotExist:
            raise template.TemplateSyntaxError(
                "'namespace' must be a existent EventConfig namespace, "
                "not '{0}'.".format(namespace)
            )

    context = {
        'today': today,
        'current_date': current_date,
        'last_month': current_date - timedelta(days=1),
        'next_month': (current_date + timedelta(days=31)).replace(day=1),
        'label': u"{0} {1}".format(MONTHS.get(int(month)), year),
        'namespace': namespace
    }

    # add css classes here instead in template
    # TODO: can configure css classes in appconfig ;)
    _calendar = build_calendar(year, month, language, namespace)
    calendar_list = []
    for day, events in _calendar.items():
        css = []
        if events:
            for event in events:
                if event.start_date == day:
                    css.append('events')
                    break
            else:
                css.append('multiday-events')
        if day.weekday() in [5, 6]:
            css.append('weekend')
        if day == today:
            css.append('today')
        # disable days that isn't from this month
        if day <= context['last_month'] or day >= context['next_month']:
            css.append('disabled')
        calendar_list.append((day, events, ' '.join(css)))
    context['calendar'] = calendar_list
    return context
Esempio n. 48
0
    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 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))
Esempio n. 50
0
 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)
Esempio n. 51
0
    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)
Esempio n. 52
0
    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
Esempio n. 53
0
    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))
Esempio n. 54
0
    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))
Esempio n. 55
0
    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('&nbsp;&nbsp;' + 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,
                                 }))
Esempio n. 56
0
    def as_dict(self):
        widget_dict = super(RemoteDateInput, self).as_dict()

        widget_dict['input_type'] = 'date'

        years = self.widget.years
        if not callable(self.widget.years):
            years = lambda: self.widget.years

        choices = [{'key': "%02d" % i, 'value': i} for i in range(1, 32)]
        day_choices = self.create_select('day', choices)

        choices = [{'key': "%02d" % i, 'value': j} for (i, j) in MONTHS.iteritems()]
        month_choices = self.create_select('month', choices)

        choices = [{'key': "%s" % i, 'value': i} for i in years()]
        year_choices = self.create_select('year', choices)

        widget_dict['choices'] = [day_choices, month_choices, year_choices]
        return widget_dict
Esempio n. 57
0
    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))