示例#1
0
	def render(self, name, value, attrs=None):
		try:
			hour_val, minute_val = value.hour, value.minute
		except AttributeError:
			hour_val = minute_val = None
			if isinstance(value, basestring):
				match = RE_TIME.match(value)
				if match:
					hour_val, minute_val = [int(v) for v in match.groups()]

		output = []

		if 'id' in self.attrs:
			id_ = self.attrs['id']
		else:
			id_ = 'id_%s' % name

		hour_choices = [(i, '%02d' % i) for i in range(0, 24)]
		if not (self.required and value):
			hour_choices.append(self.none_value)
		s = Select(choices=hour_choices)
		select_html = s.render(self.hour_field % name, hour_val)
		output.append(select_html)

		output.append(':')

		minute_choices = [(i, '%02d' % i) for i in range(0, 60)]
		if not (self.required and value):
			minute_choices.append(self.none_value)
		s = Select(choices=minute_choices)
		select_html = s.render(self.minute_field % name, minute_val)
		output.append(select_html)

		return mark_safe(u'\n'.join(output))
示例#2
0
 def render(self, name, value, attrs=None):
     if value is None: value = ''
     attrs = attrs or {}
     if attrs:
         self.attrs.update(attrs)
     
     output = []
     uf_val = ''
     uf_choices = [('','Estado')]+[(uf.pk,uf.uf) for uf in UF.objects.order_by('uf')]
     uf_select = Select(choices=uf_choices)
     municipio_select = Select(choices=(('','Cidades'),))
     
     if value:
         try:
             municipio = Municipio.objects.get(pk=value)
             uf_val = municipio.uf
             mun_choices = [(m.pk, m.nome) for m in Municipio.objects.filter(uf=uf_val).order_by('nome')]
             municipio_select = Select(choices=[('','Cidades')]+mun_choices)
         except Municipio.DoesNotExist:
             pass
     uf_attrs = self.attrs.copy()
     uf_attrs.update({"id":'%s_uf' % name, "onchange":"changeUF(this);"})
     select_html = uf_select.render('%s_uf' % name, uf_val, attrs=uf_attrs)
     required = False
     if 'class' in self.attrs:
         required = self.attrs['class'] == 'required'
     output.append(u'<label>*Local</label><div class="estado">%s%s</div>' % (required and ' class="required"' or '', select_html))#background:url(/media/images/flecha.gif) right no-repeat
     
     munic_attrs = self.attrs.copy()
     munic_attrs['style']="width:230px;"
     select_html = municipio_select.render(name, value, munic_attrs)
     output.append(u'<div class="cidade">%s%s</div>' % (required and ' class="required"' or '', select_html))
     return mark_safe(u'\n'.join(output))
示例#3
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))
示例#4
0
    def render(self, name, value, attrs=None):
        try:
            hour_val, minute_val = value.hour, value.minute
        except AttributeError:
            hour_val = minute_val = None
            if isinstance(value, basestring):
                match = RE_TIME.match(value)
                if match:
                    hour_val, minute_val = [int(v) for v in match.groups()]

        output = []

        if 'id' in self.attrs:
            id_ = self.attrs['id']
        else:
            id_ = 'id_%s' % name

        hour_choices = [(i, '%02d' % i) for i in range(0, 24)]
        if not (self.required and value):
            hour_choices.append(self.none_value)
        s = Select(choices=hour_choices)
        select_html = s.render(self.hour_field % name, hour_val)
        output.append(select_html)

        output.append(':')

        minute_choices = [(i, '%02d' % i) for i in range(0, 60)]
        if not (self.required and value):
            minute_choices.append(self.none_value)
        s = Select(choices=minute_choices)
        select_html = s.render(self.minute_field % name, minute_val)
        output.append(select_html)

        return mark_safe(u'\n'.join(output))
示例#5
0
 def render(self, name, value, attrs=None):
     if value is None: value = ''
     attrs = attrs or {}
     if attrs:
         self.attrs.update(attrs)
     
     output = []
     uf_val = ''
     uf_choices = [('','--')]+[(uf.pk,uf.uf) for uf in UF.objects.order_by('uf')]
     uf_select = Select(choices=uf_choices)
     municipio_select = Select(choices=(('','--'),))
     
     if value:
         try:
             municipio = Municipio.objects.get(pk=value)
             uf_val = municipio.uf
             mun_choices = [(m.pk, m.nome) for m in Municipio.objects.filter(uf=uf_val).order_by('nome')]
             municipio_select = Select(choices=[('','- Selecione -')]+mun_choices)
         except Municipio.DoesNotExist:
             pass
     uf_attrs = self.attrs.copy()
     uf_attrs.update({"id":'%s_uf' % name, "onchange":"changeUF(this);"})
     select_html = uf_select.render('%s_uf' % name, uf_val, attrs=uf_attrs)
     required = False
     if 'class' in self.attrs:
         required = self.attrs['class'] == 'required'
     output.append(u'<div class="field"><label%s>UF</label><br />%s</div>' % (required and ' class="required"' or '', select_html))
     
     munic_attrs = self.attrs.copy()
     munic_attrs['style']="width:250px;"
     select_html = municipio_select.render(name, value, munic_attrs)
     output.append(u'<div class="field"><label%s>Município</label><br />%s</div>' % (required and ' class="required"' or '', select_html))
     return mark_safe(u'\n'.join(output))
示例#6
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))
示例#7
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))
示例#8
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))
示例#9
0
    def render(self, name, value, attrs=None):

        try:
            hour_val, minute_val = value.hour, value.minute
        except AttributeError:
            hour_val = minute_val = None
            if isinstance(value, str):
                match = RE_TIME.match(value)
                if match:
                    hour_val, minute_val = [v for v in match.groups()]

        if "id" in self.attrs:
            id_ = self.attrs["id"]
        else:
            id_ = "id_%s" % name

        time_output = []

        #########
        # Hour #
        #########

        hour_choices = [(i, self.format_time_value(i)) for i in range(0, 24)]
        if not (self.required and value):
            hour_choices.insert(0, ("", "Hour"))
        local_attrs = self.build_attrs(self.attrs)

        s = Select(choices=hour_choices)
        select_html = s.render(self.hour_field % name, str(hour_val),
                               local_attrs)
        time_output.append(select_html)

        ##########
        # Minute #
        ##########

        minute_choices = [(i, self.format_time_value(i)) for i in range(0, 60)]
        if not (self.required and value):
            minute_choices.insert(0, ("", "Mins"))
        local_attrs = self.build_attrs(self.attrs)

        s = Select(choices=minute_choices)
        select_html = s.render(self.minute_field % name, str(minute_val),
                               local_attrs)
        time_output.append(select_html)

        time_output = """<div class="time-select">
            <div class="form__control form__control--select">%s</div>
            <div class="form__control form__control--select">%s</div>
            </div>""" % (
            time_output[0],
            time_output[1],
        )

        return mark_safe("%s" % (time_output))
示例#10
0
文件: widgets.py 项目: braskin/pd
    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))
示例#11
0
    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        attrs = attrs or {}
        if attrs:
            self.attrs.update(attrs)

        output = []
        uf_val = ''
        uf_choices = [('', '--')] + list(
            self.mun_cls.objects.values_list(
                'uf__id_ibge', 'uf_sigla').distinct().order_by('uf'))
        uf_select = Select(choices=uf_choices)
        municipio_select = Select(choices=(('', '--'), ))

        if value:
            try:
                municipio = self.mun_cls.objects.get(pk=value)
                uf_val = municipio.uf.pk
                mun_choices = [(m.pk, m.nome)
                               for m in self.mun_cls.objects.filter(
                                   uf=uf_val).order_by('nome')]
                municipio_select = Select(choices=[('', '- Selecione -')] +
                                          mun_choices)
            except self.mun_cls.DoesNotExist:
                pass
        uf_attrs = self.attrs.copy()
        uf_attrs.update({
            "id": '%s_uf' % name,
            "onchange": "changeUF(this);",
            "data-app_label": self.app_label,
            "data-object_name": self.object_name,
        })
        select_html = uf_select.render('%s_uf' % name, uf_val, attrs=uf_attrs)
        required = False
        if 'class' in self.attrs:
            required = self.attrs['class']
        # output.append(u'<div class="field"><label%s>UF</label><br />%s</div>' % (required and ' class="required"' or '', select_html))
        template_uf = get_template('municipios/uf_field.html')
        context_uf = Context({'label_class': required, 'wselect': select_html})
        output.append(template_uf.render(context_uf))

        munic_attrs = self.attrs.copy()
        munic_attrs['style'] = "width:250px;"
        select_html = municipio_select.render(name, value, munic_attrs)
        # output.append(u'<div class="field"><label%s>Município</label><br />%s</div>' % (required and ' class="required"' or '', select_html))
        template_mun = get_template('municipios/municipio_field.html')
        context_mun = Context({
            'label_class': required,
            'wselect': select_html
        })
        output.append(template_mun.render(context_mun))

        return mark_safe(u'\n'.join(output))
示例#12
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()
        month_choices = []

        for month in MONTHS:
            month_choices.append(
                (month, '{} - {}'.format(month, MONTHS[month][0:]))
            )

        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_)
        local_attrs['style'] = 'width: 130px;'

        s = Select(choices=month_choices)
        select_html = s.render(self.month_field % name, month_val, local_attrs)
        output.append(select_html)

        output.append('&nbsp;')

        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_
        local_attrs['style'] = 'width: 90px;'
        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))
示例#13
0
    def render(self, name, value, attrs=None):
        try:
            year_val, month_val, day_val, hour_val, min_val = value.year, value.month, value.day, value.hour, value.minute
        except AttributeError:
            year_val = month_val = day_val = hour_val = min_val = None
            if isinstance(value, basestring):
                match = RE_DATE.match(value)
                if match:
                    year_val, month_val, day_val, hour_val, min_val, throw_away_seconds  = [int(v) for v in match.groups()]

        date_val = "%04s-%02s-%02s" % (year_val,month_val, day_val)

        output = []

        if 'id' in self.attrs:
            id_ = self.attrs['id']
        else:
            id_ = 'id_%s' % name

        output.append("<span id=\"%s_humanreadable\"></span>" % (name))


        output.append("<input type=\"hidden\" name=\"%s\" id=\"%s\" value=\"%s\" onchange=\"updateCalendar(this);\">" % ((self.date_field % name), (self.date_field % name), date_val))

		
        output.append("<span id=\"%s_showcalendar\"><img src=\"/static/calendar.png\" alt=\"Calendar\"></span>&nbsp;&nbsp;&nbsp;" % (name));
        output.append("""<script>Event.observe(window, 'load', function(event) {  Calendar.setup({dateField : '%s',triggerElement : '%s_showcalendar'})});</script>""" % ((self.date_field % name), name))
        output.append("""<script>Event.observe(window, 'load', function(event) {  updateCalendar($(\"%s\")); });</script>""" % ((self.date_field % name)))

        hour_choices = [(i, i) for i in range(0, 23)]
        #if not (self.required and value):
        #    hour_choices.insert(0, self.none_value)
        local_attrs = self.build_attrs(id=self.hour_field % id_)
        s = Select(choices=hour_choices)
        select_html = s.render(self.hour_field % name, hour_val, local_attrs)
        output.append(select_html)

        output.append(":");

        min_choices = [(i, i) for i in range(0, 59)]
        #if not (self.required and value):
        #    hour_choices.insert(0, self.none_value)
        local_attrs['id'] = self.min_field % id_
        s = Select(choices=min_choices)
        select_html = s.render(self.min_field % name, min_val, local_attrs)
        output.append(select_html)

        return mark_safe(u'\n'.join(output))
示例#14
0
    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        attrs = attrs or {}
        if attrs:
            self.attrs.update(attrs)

        output = []
        uf_val = ''
        uf_choices = [('', '--')] + list(self.mun_cls.objects.values_list('uf__id_ibge', 'uf_sigla').distinct().order_by('uf_sigla'))
        uf_select = Select(choices=uf_choices)
        municipio_select = Select(choices=(('', '--'),))

        if value:
            try:
                municipio = self.mun_cls.objects.get(pk=value)
                uf_val = municipio.uf.pk
                mun_choices = [(m.pk, m.nome) for m in self.mun_cls.objects.filter(uf=uf_val).order_by('nome')]
                municipio_select = Select(choices=[('', '- Selecione -')] + mun_choices)
            except self.mun_cls.DoesNotExist:
                pass
        uf_attrs = self.attrs.copy()
        uf_attrs.update(
            {
                "id": '%s_uf' % name,
                "onchange": "changeUF(this);",
                "data-app_label": self.app_label,
                "data-object_name": self.object_name,
            }
        )
        select_html = uf_select.render('%s_uf' % name, uf_val, attrs=uf_attrs)
        required = False
        if 'class' in self.attrs:
            required = self.attrs['class']
        # output.append(u'<div class="field"><label%s>UF</label><br />%s</div>' % (required and ' class="required"' or '', select_html))
        template_uf = get_template('municipios/uf_field.html')
        context_uf = {'label_class': required, 'wselect': select_html}
        output.append(template_uf.render(context_uf))

        munic_attrs = self.attrs.copy()
        munic_attrs['style'] = "width:250px;"
        select_html = municipio_select.render(name, value, munic_attrs)
        # output.append(u'<div class="field"><label%s>Município</label><br />%s</div>' % (required and ' class="required"' or '', select_html))
        template_mun = get_template('municipios/municipio_field.html')
        context_mun = {'label_class': required, 'wselect': select_html}
        output.append(template_mun.render(context_mun))

        return mark_safe(u'\n'.join(output))
示例#15
0
文件: widgets.py 项目: eeriks/velo.lv
    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))
示例#16
0
    def change_template_widget(self):
        change_template_options = sorted(get_templates(self.obj.__class__), key=lambda x: x[1])

        widget = Select(attrs={
            'id': 'id_template_name',
        }, choices=change_template_options)

        return widget.render(name='template_name', value=self.layout._meta.template)
示例#17
0
 def head_index_box(self):
     from django.forms.widgets import Select
     choices = [(0, 'Unknown')]
     for i, daughter in enumerate(self.expansion.rule[1:-1].split()[1:]):
         choices.append((i+1, str(i+1) + ': ' + daughter))
     s = Select(choices=choices)
     return s.render('expansion-'+str(self.expansion.id) + '-headindex',
             self.head_index)
示例#18
0
 def create_select(self, name, field, val, choices):
     if 'id' in self.attrs:
         id_ = self.attrs['id']
     else:
         id_ = 'id_%s' % name
     local_attrs = self.build_attrs(id=field % id_)
     s = Select(choices=choices)
     select_html = s.render(field % name, val, local_attrs)
     return select_html
    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))
示例#20
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))
示例#21
0
 def create_select(self, name, field, value, val, choices):
     if 'id' in self.attrs:
         id_ = self.attrs['id']
     else:
         id_ = 'id_%s' % name
     if not (self.required and value):
         choices.insert(0, self.none_value)
     local_attrs = self.build_attrs(id=field % id_)
     s = Select(choices=choices)
     select_html = s.render(field % name, val, local_attrs)
     return select_html
 def create_select(self, name, field, value, val, choices):
     if 'id' in self.attrs:
         id_ = self.attrs['id']
     else:
         id_ = 'id_%s' % name
     if not (self.required and val):
         choices.insert(0, self.none_value)
     local_attrs = self.build_attrs(id=field % id_)
     s = Select(choices=choices)
     select_html = s.render(field % name, val, local_attrs)
     return select_html
    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))
示例#24
0
    def render(self, name, value, attrs=None):
        if value is None: value = ''
        attrs = attrs or {}
        if attrs:
            self.attrs.update(attrs)

        output = []
        uf_val = ''
        uf_choices = [('', '--')] + [(uf.pk, uf.uf)
                                     for uf in UF.objects.order_by('uf')]
        uf_select = Select(choices=uf_choices)
        municipio_select = Select(choices=(('', '--'), ))

        if value:
            try:
                municipio = Municipio.objects.get(pk=value)
                uf_val = municipio.uf.pk
                mun_choices = [(m.pk, m.nome)
                               for m in Municipio.objects.filter(
                                   uf=uf_val).order_by('nome')]
                municipio_select = Select(choices=[('', '- Selecione -')] +
                                          mun_choices)
            except Municipio.DoesNotExist:
                pass
        uf_attrs = self.attrs.copy()
        uf_attrs.update({"id": '%s_uf' % name, "onchange": "changeUF(this);"})
        select_html = uf_select.render('%s_uf' % name, uf_val, attrs=uf_attrs)
        required = False
        if 'class' in self.attrs:
            required = self.attrs['class'] == 'required'
        output.append(u'<div class="field"><label%s>UF</label><br />%s</div>' %
                      (required and ' class="required"' or '', select_html))

        munic_attrs = self.attrs.copy()
        munic_attrs['style'] = "width:250px;"
        select_html = municipio_select.render(name, value, munic_attrs)
        output.append(
            u'<div class="field"><label%s>Município</label><br />%s</div>' %
            (required and ' class="required"' or '', select_html))
        return mark_safe(u'\n'.join(output))
示例#25
0
    def __init__(self, parent):
        child_options = [UNSELECTED_OPTION]
        self.subject_selects = []
        for child in parent.home.children.all():
            child_options.append((child.pk, get_user_label(child)))
            subject_options = [(subjectroom.pk, subjectroom.subject.name) for subjectroom in
                               child.subjects_enrolled_set.all()]
            subject_select = Select({'id': 'subject-select-' + str(child.pk)},
                                    subject_options)
            self.subject_selects.append(subject_select.render('subject_child' + str(child.pk), 0))

        self.child_select = Select({'class': SELECT_CHOSEN_CLASS, 'id': 'child-select'},
                                   child_options).render('child', 0)
示例#26
0
def rappel(modeladmin, request, queryset):

    opts = modeladmin.model._meta
    app_label = opts.app_label

    if request.POST.get('post'):

        today = datetime.date.today()
        lastyear = today - datetime.timedelta(days=365)

        modele_id = request.POST.get('modele')
        rappelmodele = RappelModele.objects.get(pk=modele_id)

        rappel = Rappel()
        rappel.user_creation = request.user
        rappel.date_cible = lastyear
        rappel.date_limite = today + datetime.timedelta(days=30)
        rappel.sujet = rappelmodele.sujet
        rappel.contenu = rappelmodele.contenu
        rappel.save()

        for chercheur in queryset:
            rappeluser = RappelUser()
            rappeluser.rappel = rappel
            rappeluser.user = chercheur.user
            rappeluser.save()

        n = queryset.count()

        if n == 1:
            message = u"1 rappel a été envoyé."
        else:
            message = u"%(count)d rappels ont été envoyés." % {"count": n}

        modeladmin.message_user(request, message)

        return None

    select = Select(choices=RappelModele.objects.values_list('id', 'nom'))

    context = {
        "title": _("Are you sure?"),
        "queryset": queryset,
        "templateselect": select.render("modele", ''),
        "app_label": app_label,
        "opts": opts,
        "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME,
    }

    return render_to_response("admin/rappels/chercheurrappel/rappel_selected_confirmation.html",
        context, context_instance=template.RequestContext(request))
示例#27
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 = [(num, month.capitalize()) for num, month in MONTHS.items()]
        month_choices.sort()
        local_attrs = self.build_attrs(id=self.month_field % id_)
        s = Select(choices=month_choices)
        # Hacky: Jan 02 is a guard date that signifies that the resume
        # had listed only the year.  Burning Glass interprets year only
        # durations as Jan 01 of that year.
        # See https://github.ksjc.sh.colo/apps-team/web-resumes/issues/71
        if hasattr(value, 'day') and value.month == 1 and value.day == 2:
            select_html = s.render(self.month_field % name, '', local_attrs)
        else:
            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]
        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))
示例#28
0
    def __init__(self):
        subjectrooms = self.get_subjectrooms()

        subjectroom_options = [UNSELECTED_OPTION]
        self.student_selects = []
        for subjectroom in subjectrooms:
            subjectroom_options.append((subjectroom.pk, get_subjectroom_label(subjectroom)))
            student_options = [(student.pk, get_user_label(student)) for student in subjectroom.students.all()]
            student_options.insert(0, (0, "Full Class"))
            student_select = Select({'id': 'student-select-' + str(subjectroom.pk)}, student_options)
            self.student_selects.append(student_select.render('student_subjectroom' + str(subjectroom.pk), 0))

        self.subjectroom_select = Select({'class': SELECT_CHOSEN_CLASS, 'id': 'subjectroom-select'},
                                         subjectroom_options).render('subjectroom', 0)
示例#29
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

        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))
示例#30
0
文件: forms.py 项目: SciPost/SciPost
    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, (str, bytes)):
                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

        if hasattr(self, 'month_choices'):
            local_attrs = self.build_attrs({'id': self.month_field % id_})
            s = Select(choices=self.month_choices,
                       attrs={'class': 'form-control'})
            select_html = s.render(self.month_field % name, month_val,
                                   local_attrs)
            output.append(self.sqeeze_form_group(select_html))

        if hasattr(self, 'year_choices'):
            local_attrs = self.build_attrs({'id': self.year_field % id_})
            s = Select(choices=self.year_choices,
                       attrs={'class': 'form-control'})
            select_html = s.render(self.year_field % name, year_val,
                                   local_attrs)
            output.append(self.sqeeze_form_group(select_html))

        return mark_safe(u'\n'.join(output))
示例#31
0
 def create_select(self, name, field, val, choices):
     """
     Creates a "select" field with a given name, populated list of
     choices and a chosen value.
     """
     if 'id' in self.attrs:
         id_ = self.attrs['id']
     else:
         id_ = 'id_%s' % name
     if not (self.required and val):
         choices.insert(0, self.none_value)
     local_attrs = self.build_attrs(id=field % id_)
     s = Select(choices=choices)
     select_html = s.render(field % name, val, local_attrs)
     return select_html
示例#32
0
def dashboard(request):
  queryset = Exercise.objects.all().order_by('name')
  exercises = []

  for row in queryset:
    tmp_tpl = (row.id, row.name)
    exercises.append(tmp_tpl)

  select = Select(choices=exercises, attrs={'id':'exercise_id'})
  exercise_select = select.render('exercise', 1) # 1 = push ups

  rows = Set.objects.filter(user = request.user).order_by('ts')

  rep_counts = {}

  reps_remaining = 36525;

  for row in rows:
    pprint(row)
    pprint(row.reps)
    pprint(row.exercise.name)
    if not row.exercise.name in rep_counts:
      rep_counts[row.exercise.name] = row.reps
    else:
      rep_counts[row.exercise.name] += row.reps

    reps_remaining -= row.reps

  pprint(rep_counts)






  context = {
    'exercise_select' : exercise_select,
    'rep_counts': rep_counts,
    'reps_remaining': reps_remaining
  }

  return render(request, 'web/dashboard.html', context)
示例#33
0
 def render(self, name, value, attrs=None, renderer=None):
     nr = [(None, "Patron non répertorié")]
     if value:
         pattern = Pattern.objects.get(id=value)
         creator_id = pattern.creator_id
         self.choices = [(value, pattern.name)]
     else:
         creator_id = 0
         self.choices = nr
     creator_qs = PatternCreator.objects\
         .annotate(pattern_count=Count('patterns'))\
         .filter(pattern_count__gt=0)
     preselect = Select(choices=nr +
                        list(creator_qs.values_list('id', 'name')))
     prefix_id = 'id_pattern_creator'
     prefix = preselect.render(name='',
                               value=creator_id,
                               attrs={'id': prefix_id})
     attrs = attrs or {}
     attrs['data-prefix-id'] = prefix_id
     result = super().render(name, value, attrs=attrs, renderer=renderer)
     return '\n'.join([prefix, result])
示例#34
0
    def render(self, name, value, attrs=None):
        try:
            month_val = value.month
        except AttributeError:
            try:
                month_val = datetime.datetime.strptime(value, "%Y-%m-%d").month
            except TypeError:
                month_val = None

        output = []

        if "id" in self.attrs:
            id_ = self.attrs["id"]
        else:
            id_ = "id_%s" % name

        month_choices = (
            (0, "---"),
            (1, "Januari"),
            (2, "Februari"),
            (3, "Maart"),
            (4, "April"),
            (5, "Mei"),
            (6, "Juni"),
            (7, "Juli"),
            (8, "Augustus"),
            (9, "September"),
            (10, "Oktober"),
            (11, "November"),
            (12, "December"),
        )
        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)

        return mark_safe(u"\n".join(output))
示例#35
0
    def render(self, name, value, attrs=None):

        try:
            year_val, month_val, day_val, hour_val, minute_val = value.year, value.month, value.day, value.hour, value.minute
        except AttributeError:
            year_val = month_val = day_val = hour_val = minute_val = None
            if isinstance(value, str):
                match = RE_DATE.match(value)
                if match:
                    year_val, month_val, day_val, hour_val, minute_val = [
                        int(v) for v in match.groups()
                        ]

        if 'id' in self.attrs:
            id_ = self.attrs['id']
        else:
            id_ = 'id_%s' % name

        date_output = []
        time_output = []

        #########
        # Day   #
        #########

        day_choices = [(i, i) for i in range(1, 32)]
        if not (self.required and value):
            day_choices.insert(0, (0, 'Day'))

        local_attrs = self.build_attrs(self.attrs)

        s = Select(choices=day_choices)
        select_html = s.render(self.day_field % name, day_val, local_attrs)
        date_output.append(select_html)

        #########
        # Month #
        #########

        month_choices = tuple(MONTHS.items())
        if not (self.required and value):
            month_choices = ((0, 'Month'),) + month_choices
        local_attrs['id'] = self.month_field % id_

        s = Select(choices=month_choices)
        select_html = s.render(self.month_field % name, month_val, local_attrs)
        date_output.append(select_html)

        #########
        # Year  #
        #########

        year_choices = [(i, i) for i in self.years]
        if not (self.required and value):
            year_choices.insert(0, (0, 'Year'))
        local_attrs['id'] = self.year_field % id_
        s = Select(choices=year_choices)
        select_html = s.render(self.year_field % name, year_val, local_attrs)
        date_output.append(select_html)

        #########
        # Hour #
        #########

        hour_choices = [(i, self.format_time_value(i)) for i in range(0, 23)]
        if not (self.required and value):
            hour_choices.insert(0, ('', 'Hour'))
        local_attrs = self.build_attrs(self.attrs)

        s = Select(choices=hour_choices)
        select_html = s.render(self.hour_field % name, hour_val, local_attrs)
        time_output.append(select_html)

        ##########
        # Minute #
        ##########

        minute_choices = [(i, self.format_time_value(i)) for i in range(0, 59)]
        if not (self.required and value):
            minute_choices.insert(0, ('', 'Minute'))
        local_attrs = self.build_attrs(self.attrs)

        s = Select(choices=minute_choices)
        select_html = s.render(
            self.minute_field % name, minute_val, local_attrs)
        time_output.append(select_html)

        date_output = """<div class="date-select">
            <div class="form__control form__control--select">%s</div>
            <div class="form__control form__control--select">%s</div>
            <div class="form__control form__control--select">%s</div>
            </div>""" % (date_output[0], date_output[1], date_output[2])

        time_output = """<div class="time-select">
            <div class="form__control form__control--select">%s</div>
            <div class="form__control form__control--select">%s</div>
            </div>""" % (time_output[0], time_output[1])

        return mark_safe(u'%s%s' % (date_output, time_output))
示例#36
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 = []

        start_date = now - relativedelta(months=self.month_range)
        end_date = now + relativedelta(months=self.month_range)

        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)
        block_html = """<span class='%(class)s day'>%(select_html)s</span>"""
        output.append(block_html % {
            'class': local_attrs['class'],
            'select_html': select_html,
        })

        yearmonth_choices = []
        ddate = start_date
        while ddate < end_date:
            yearmonth_choices.append(
                ('%s-%s' % (ddate.year, ddate.month), '%s %s' %
                 (unicode(capfirst(MONTHS[ddate.month])), ddate.year)))
            ddate = ddate + relativedelta(months=1)
        if not (self.required and value):
            yearmonth_choices.append(self.none_value)

        local_attrs['id'] = self.yearmonth_field % id_
        s = Select(choices=yearmonth_choices)
        select_html = s.render(self.yearmonth_field % name,
                               '%s-%s' % (year_val, month_val), local_attrs)
        block_html = """<span class='%(class)s yearmonth'>%(select_html)s</span>"""
        output.append(block_html % {
            'class': local_attrs['class'],
            'select_html': select_html,
        })

        local_attrs['id'] = self.datepicker_field % id_
        i = HiddenInput()
        input_html = i.render(self.datepicker_field % name, None, local_attrs)
        output.append(input_html)

        other_html = render_to_string(
            'adlibre/contrib/widgets/selectdatewidget.html', {
                'id_datepicker_field': self.datepicker_field % id_,
                'id_day_field': self.day_field % id_,
                'id_yearmonth_field': self.yearmonth_field % id_,
                'class': local_attrs['class'],
                'month_range': self.month_range,
            })
        output.append(other_html)

        return mark_safe(u'\n'.join(output))
    def render(self, name, value, attrs=None):
        try:  # try to get time values from a datetime.time object (value)
            hour_val, minute_val, second_val = value.hour, value.minute, value.second
            if self.twelve_hr:
                if hour_val >= 12:
                    self.meridiem_val = 'p.m.'
                else:
                    self.meridiem_val = 'a.m.'
        except AttributeError:
            hour_val = minute_val = second_val = 0
            if isinstance(value, string_types):
                match = RE_TIME.match(value)
                if match:
                    time_groups = match.groups()
                    hour_val = int(
                        time_groups[HOURS]) % 24  # force to range(0-24)
                    minute_val = int(time_groups[MINUTES])
                    if time_groups[SECONDS] is None:
                        second_val = 0
                    else:
                        second_val = int(time_groups[SECONDS])

                    # check to see if meridiem was passed in
                    if time_groups[MERIDIEM] is not None:
                        self.meridiem_val = time_groups[MERIDIEM]
                    else:  # otherwise, set the meridiem based on the time
                        if self.twelve_hr:
                            if hour_val >= 12:
                                self.meridiem_val = 'p.m.'
                            else:
                                self.meridiem_val = 'a.m.'
                        else:
                            self.meridiem_val = None

        # If we're doing a 12-hr clock, there will be a meridiem value, so make sure the
        # hours get printed correctly
        if self.twelve_hr and self.meridiem_val:
            if self.meridiem_val.lower().startswith(
                    'p') and hour_val > 12 and hour_val < 24:
                hour_val = hour_val % 12
        elif hour_val == 0:
            hour_val = 12

        output = []
        if 'id' in self.attrs:
            id_ = self.attrs['id']
        else:
            id_ = 'id_%s' % name

        # For times to get displayed correctly, the values MUST be converted to unicode
        # When Select builds a list of options, it checks against Unicode values
        hour_val = u"%.2d" % hour_val
        minute_val = u"%.2d" % minute_val
        second_val = u"%.2d" % second_val

        hour_choices = [("%.2d" % i, "%.2d" % i) for i in self.hours]
        # local_attrs = self.build_attrs(id=self.hour_field % id_)

        local_attrs = self.attrs
        local_attrs['id'] = self.hour_field % id_
        s = Select(choices=hour_choices)
        select_html = s.render(self.hour_field % name, hour_val, local_attrs)
        output.append(select_html)

        minute_choices = [("%.2d" % i, "%.2d" % i) for i in self.minutes]
        local_attrs['id'] = self.minute_field % id_
        select_html = Select(choices=minute_choices).render(
            self.minute_field % name, minute_val, local_attrs)
        output.append(select_html)

        second_choices = [("%.2d" % i, "%.2d" % i) for i in self.seconds]
        local_attrs['id'] = self.second_field % id_
        select_html = Select(choices=second_choices).render(
            self.second_field % name, second_val, local_attrs)
        output.append(select_html)

        if self.twelve_hr:
            #  If we were given an initial value, make sure the correct meridiem gets selected.
            if self.meridiem_val is not None and self.meridiem_val.startswith(
                    'p'):
                meridiem_choices = [('p.m.', 'p.m.'), ('a.m.', 'a.m.')]
            else:
                meridiem_choices = [('a.m.', 'a.m.'), ('p.m.', 'p.m.')]

            local_attrs['id'] = local_attrs['id'] = self.meridiem_field % id_
            select_html = Select(choices=meridiem_choices).render(
                self.meridiem_field % name, self.meridiem_val, local_attrs)
            output.append(select_html)

        return mark_safe(u'\n'.join(output))
示例#38
0
文件: widgets.py 项目: MVReddy/TMS
    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 = []

        start_date = now - relativedelta(months=self.month_range)
        end_date = now + relativedelta(months=self.month_range)

        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)
        block_html = """<span class='%(class)s day'>%(select_html)s</span>"""
        output.append(block_html % {
            'class': local_attrs['class'],
            'select_html': select_html,
            })

        yearmonth_choices = []
        ddate = start_date
        while ddate < end_date:
            yearmonth_choices.append(('%s-%s' % (ddate.year, ddate.month), '%s %s' % (unicode(capfirst(MONTHS[ddate.month])), ddate.year)))
            ddate = ddate + relativedelta(months=1)
        if not (self.required and value):
            yearmonth_choices.append(self.none_value)

        local_attrs['id'] = self.yearmonth_field % id_
        s = Select(choices=yearmonth_choices)
        select_html = s.render(self.yearmonth_field % name, '%s-%s' % (year_val, month_val), local_attrs)
        block_html = """<span class='%(class)s yearmonth'>%(select_html)s</span>"""
        output.append(block_html % {
            'class': local_attrs['class'],
            'select_html': select_html,
            })

        local_attrs['id'] = self.datepicker_field % id_
        i = HiddenInput()
        input_html = i.render(self.datepicker_field % name, None, local_attrs)
        output.append(input_html)

        other_html = render_to_string('adlibre/contrib/widgets/selectdatewidget.html', {
            'id_datepicker_field': self.datepicker_field % id_,
            'id_day_field': self.day_field % id_,
            'id_yearmonth_field': self.yearmonth_field % id_,
            'class': local_attrs['class'],
            'month_range': self.month_range,
            })
        output.append(other_html)

        return mark_safe(u'\n'.join(output))
示例#39
0
    def pattern_selectors(self):
        # This method became complicated, hence this comment. What are we trying to achieve here?
        #
        # Of course, we want a list of pattern creators. But also, if we have selected a creator,
        # we want its list of patterns. So there's that. Simple, right?
        #
        # But it's not over! We also want to avoid having our creator list polluted by patternless
        # creators (there are a couple of them in the DB), so our creator_qs has to be beefed up.
        #
        # But wait! now we have is_free and is_jersey flags. We want these to affect the list of
        # patterns and creators available for selection. *this* particularly complicates this
        # and make creator_qs much more complex.

        item_all = [(0, "Tous")]

        def pop(key):
            val = params.pop(key, None)
            if isinstance(val, list):
                val = val[0] if val else None
            return val

        params = self.request.GET.copy()
        params['page'] = '1'

        pattern_id = pop('pattern')
        pattern_creator_id = pop('pattern_creator')
        if pattern_id and Pattern.objects.filter(id=pattern_id).exists():
            # More reliable than the request argument.
            pattern_creator_id = Pattern.objects.get(id=pattern_id).creator.id

        pattern_filters = {
            v.replace('pattern_', ''): True
            for v in self.pattern_checkboxes().get_selected_options()
        }
        pattern_qs = Pattern.objects.filter(**pattern_filters)

        # Woah, complicated...
        # https://stackoverflow.com/a/30753074
        pattern_sub = Subquery(
            pattern_qs.filter(creator_id=OuterRef('pk')).annotate(
                cnt=Count('pk')).values('cnt')[:1],
            output_field=IntegerField())
        creator_filter = Q(pattern_count__gt=0)

        # We always want a selected creator to show up, even if it has no pattern
        if pattern_creator_id:
            creator_filter |= Q(id=pattern_creator_id)

        creator_qs = PatternCreator.objects\
            .annotate(pattern_count=pattern_sub)\
            .filter(creator_filter)

        get_url = '?{}&pattern_creator='.format(params.urlencode())
        widget = Select(
            attrs={'data-get-url': get_url},
            choices=item_all + list(creator_qs.values_list('id', 'name')),
        )
        result = [
            widget.render(
                name='pattern_creator',
                value=pattern_creator_id,
            )
        ]

        if pattern_creator_id and creator_qs.filter(
                id=pattern_creator_id).exists():
            pattern_creator = PatternCreator.objects.get(id=pattern_creator_id)
            pattern_qs = pattern_qs.filter(creator=pattern_creator)
            params['pattern_creator'] = pattern_creator_id
            get_url = '?{}&pattern='.format(params.urlencode())
            widget = Select(
                attrs={'data-get-url': get_url},
                choices=item_all + list(pattern_qs.values_list('id', 'name')),
            )
            result.append(widget.render(
                name='pattern',
                value=pattern_id,
            ))

        return result
示例#40
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()
                    ]

        if "id" in self.attrs:
            id_ = self.attrs["id"]
        else:
            id_ = "id_%s" % name

        date_output = []

        #########
        # Day   #
        #########

        day_choices = [(i, i) for i in range(1, 32)]
        if not (self.required and value):
            day_choices.insert(0, (0, "Day"))

        local_attrs = self.build_attrs(self.attrs)

        s = Select(choices=day_choices)
        select_html = s.render(self.day_field % name, day_val, local_attrs)
        date_output.append(select_html)

        #########
        # Month #
        #########

        month_choices = tuple(MONTHS.items())
        if not (self.required and value):
            month_choices = ((0, "Month"), ) + month_choices
        local_attrs["id"] = self.month_field % id_

        s = Select(choices=month_choices)
        select_html = s.render(self.month_field % name, month_val, local_attrs)
        date_output.append(select_html)

        #########
        # Year  #
        #########

        year_choices = [(i, i) for i in self.years]
        if not (self.required and value):
            year_choices.insert(0, (0, "Year"))
        local_attrs["id"] = self.year_field % id_
        s = Select(choices=year_choices)
        select_html = s.render(self.year_field % name, year_val, local_attrs)
        date_output.append(select_html)

        return mark_safe("""<div class="date-select">
            <div class="form__control form__control--select">%s</div>
            <div class="form__control form__control--select">%s</div>
            <div class="form__control form__control--select">%s</div>
            </div>""" % (date_output[0], date_output[1], date_output[2]))
示例#41
0
 def render(self):
     se = Select(choices=self.options)
     name = "stateselect"
     return se.render("stateselect", self.val, attrs={"id": "id-state-select"})
示例#42
0
class BootstrapDropdown(Select):
  select_option_template = """<option id="%(name)s-option-%(value)s" value="%(value)s" %(option_selected_html)s>%(label)s</option>"""
  list_item_template = """<li id="%(name)s-list-item-%(value)s" name="%(name)s" data-label="%(label)s" rel="%(value)s" class="select-list-item %(list_selected_html)s"><a class="" tabindex="-1"><span class="pull-left">%(label)s</span></a></li>"""
  html_template = ("""
      <select%(attrs)s style="display: none;">
        %(select_options)s
      </select>
      <div class="btn-group select">
        <button id="%(name)s-button" data-toggle="dropdown" class="btn dropdown-toggle clearfix btn-small btn-primary">
          <span id="select-label-%(name)s" class="filter-option pull-left">%(label)s</span>&nbsp;<span class="caret"></span>
        </button>
        <i class="dropdown-arrow dropdown-arrow-inverse"></i>
        <ul id="%(name)s-dropdown-menu" role="menu" class="dropdown-menu dropdown-inverse" style="overflow-y: auto; min-height: 108px;">
          %(list_items)s
        </ul>
      </div>
    
    """)
  attrs = {}
  label=None
  selected_label = None
  def get_help_text(self, str): pass
  #   if not str: return ""
  #   return ' data-original-title="%s" title="%s"' % (str,str)
  def add_attrs(self, attrs):
    # merges attributes passed into init with those included with class definition
    if not attrs: return self.attrs
    for key, value in self.attrs.items():
        if key in attrs: attrs[key]+=" "+value
        else: attrs[key]=value
    # Add in btn-size if set
    # if self.btn_size:
    #     if 'class' in attrs: attrs['class']+='btn-'+self.btn_size
    #     else: attrs['class']='btn-'+self.btn_size
    return attrs
  def __init__(self, *args, **kwargs):
    attrs = kwargs.pop('attrs',{})
    # print "kwargs = %s" % str(kwargs)
    label = kwargs.pop('label', None)
    help_text = self.get_help_text(kwargs.pop('help_text',None))
    # self.btn_size = kwargs.pop('btn_size',None)
    attrs = self.add_attrs(attrs)
    choices = kwargs.pop('choices',())
    self.noscript_widget = Select(attrs={}, choices=choices)
    super(BootstrapDropdown, self).__init__(attrs, choices)
    self.help_text = help_text
    # print "label = %s" % str(label)
    self.label=label
    # print "self.label = %s" % str(self.label)
    # print "self.help_text = %s" % str(self.help_text)
    
  def __setattr__(self, k, value):
    super(BootstrapDropdown, self).__setattr__(k, value)
    if k != 'attrs':
        self.noscript_widget.__setattr__(k, value)
  def get_label(self):
    # print "self.label = %s" % str(self.label)
    if self.label: label = self.label
    elif self.name: label = self.name.title()
    if label:

      if self.value and self.selected_label: label+= ': %s' % self.selected_label
      return label
    else:
      return _(u'Select an option')
  def get_context(self, final_attrs, choices, value, name):
    # print "====================self.label = %s" % str(self.label)
    # print "self.get_label() = %s" % str(self.get_label())
    self.value=value
    options=self.render_options(choices, [value])
    return {
      'attrs': flatatt(final_attrs),
      'select_options':options['select'],
      'list_items':options['list'],
      'label': self.get_label(),
      'name': name,
      'help_text':self.help_text,
      'noscript': self.noscript_widget.render(name, value, {}, choices)
      }
  def render(self, name, value, attrs=None, choices=()):
    self.name = name
    # print "attrs = %s" % str(attrs)
    attrs = self.add_attrs(attrs)
    # print "self.help_text = %s" % str(self.help_text)
    # print "attrs = %s" % str(attrs)
    # print "value = %s" % str(value)

    if value is None: value = ''
    final_attrs = self.build_attrs(attrs, name=name)
    output = [self.html_template % self.get_context(final_attrs, choices, value, name)]
    return mark_safe(u'\n'.join(output))
  def get_option_context(self, option_value, selected_html, option_label):
    label = conditional_escape(force_unicode(option_label)) or "None"
    if selected_html: 
      list_selected='selected'
      self.selected_label=label
    else: list_selected = ""
    return {
      'value':escape(option_value),
      'option_selected_html': selected_html,
      'list_selected_html':list_selected,
      'name':self.name,
      'label':label
      }
  def render_option(self, selected_choices, option_value, option_label):
    option_value = force_unicode(option_value)
    selected_html = (option_value in selected_choices) and u' selected="selected"' or ''
    context = self.get_option_context(option_value, selected_html, option_label)
    select_option_output = self.select_option_template % context
    list_item_output = self.list_item_template % context
    return {'list_item':list_item_output, 'select_option':select_option_output}

  def render_options(self, choices, selected_choices):
    # Normalize to strings.
    selected_choices = set([force_unicode(v) for v in selected_choices])
    output = {'list':[],'select':[]}
    for option_value, option_label in chain(self.choices, choices):
      if isinstance(option_label, (list, tuple)):
        for option in option_label:
          output.append(self.render_option(selected_choices, *option))
      else:
        o = self.render_option(selected_choices, option_value, option_label)
        output['list'].append(o['list_item'])
        output['select'].append(o['select_option'])
    output['list'] = u'\n'.join(output['list'])
    output['select'] = u'\n'.join(output['select'])
    return output