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))
def render(self, name, value, attrs=None): try: year_val, month_val = value.year, value.month except AttributeError: year_val = month_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name local_attrs = self.build_attrs(id=self.month_field % id_) month_choices = MONTHS.items() month_choices.insert(0, self.none_value) #month_choices.sort() s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) year_choices = [(i, i) for i in self.years] year_choices.insert(0, self.none_value) local_attrs['id'] = self.year_field % id_ s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(select_html) return mark_safe(u'\n'.join(output))
def 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))
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))
def render(self, name, value, attrs=None): try: y_val, m_val = value.year, value.month except AttributeError: y_val = m_val = None if isinstance(value, str): match = RE_DATE.match(value) if match: y_val, m_val, d_val = [int(v) for v in match.groups()] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name month_choices = list(MONTHS.items()) if not (self.required and value): month_choices.append(self.none_value_month) month_choices.sort() local_attrs = self.build_attrs(id=self.month_field % id_) s = Select(choices=month_choices) select_html = s.render(self.month_field % name, m_val, local_attrs) output.append('<div class="date-select">' + select_html + '</div>') year_choices = [(i, i) for i in self.years] if not (self.required and value): year_choices.insert(0, self.none_value_year) local_attrs['id'] = self.year_field % id_ s = Select(choices=year_choices) select_html = s.render(self.year_field % name, y_val, local_attrs) output.append('<div class="date-select">' + select_html + '</div>') return mark_safe(u'\n'.join(output))
def 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)
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)
def render_options(self, object_selected): s = Select() if self.t_widget == 'autocomplete': choices = [( getattr(object_selected, self.name_value[0]), getattr(object_selected, self.name_value[1]) )] return s.render_options(choices, (object_selected.id, )) return s.render_options(self.get_choices(), (object_selected.id, ))
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 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(' ') 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))
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))
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
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> " % (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))
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))
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
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))
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))
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))
class GrupamentoForm(forms.ModelForm): class Meta: model = Grupamento exclude = ('user', ) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(GrupamentoForm, self).__init__(*args, **kwargs) self.fields['ativo'].queryset = Ativo.objects.filter(user=self.user, quantidade__gt=0) ativo = forms.ModelChoiceField( queryset=None, widget=Select( attrs={ 'data-live-search': 'true', 'Class': 'selectpicker border rounded', 'autofocus': '' })) data = forms.DateField( widget=DatePickerInput(format='%d/%m/%Y', options={'locale': 'pt-br'}, attrs={'placeholder': 'DD/MM/AAAA'}))
class Meta: model = SaleItem exclude = ['sale'] widgets = { 'product': Select(attrs={ 'class': 'required form-control', 'data-placeholder': 'Product' }, ), 'qty': TextInput(attrs={ 'class': 'required number form-control', 'placeholder': 'Qty' }), } error_messages = { 'product': { 'required': _("Product field is required."), }, 'qty': { 'required': _("Qauntity field is required."), }, }
class AlternativeEmailsForm(ModelEditForm): notifications = CharField(required=False, widget=Select(choices=((True, 'Yes'), (False, 'No')))) def __init__(self, *args, **kwargs): super(AlternativeEmailsForm, self).__init__(*args, **kwargs) self.fields['notifications'].initial = \ self.instance.portal_notifications def clean_notifications(self): response = self.cleaned_data.get('notifications', None) self.instance.portal_notifications = True if response else False return response class Meta: model = AlternativeEmail fields = ['email', 'type', 'notifications', 'comment'] widgets = { 'email': EmailInput(), 'type': Select(choices=Email.TYPES), }
class IssueBankCommissionForm(Form): bg_sum = DecimalField(decimal_places=2, required=True, localize=True) bg_start_date = DateField(required=True) bg_end_date = DateField(required=True) bg_is_benefeciary_form = BooleanField(required=False, widget=Select(attrs={'class': 'form-control'}, choices=[ (True, 'Да'), (False, 'Нет'), ])) tender_has_prepayment = BooleanField(required=False) bg_type = ChoiceField(required=True, choices=[ (consts.BG_TYPE_CONTRACT_EXECUTION, 'Исполнение контракта'), (consts.BG_TYPE_APPLICATION_ENSURE, 'Обеспечение заявки на участие в тендере'), (consts.BG_TYPE_REFUND_OF_ADVANCE, 'Возврат аванса'), (consts.BG_TYPE_WARRANTY_ENSURE, 'Обеспечение гарантийных обязательств') ]) tender_exec_law = ChoiceField(required=True, choices=[ (consts.TENDER_EXEC_LAW_44_FZ, '44-ФЗ'), (consts.TENDER_EXEC_LAW_223_FZ, '223-ФЗ'), (consts.TENDER_EXEC_LAW_185_FZ, '185-ФЗ'), (consts.TENDER_EXEC_LAW_COMMERCIAL, 'Коммерческий'), (consts.TENDER_EXEC_LAW_CUSTOMS, 'Таможенная'), (consts.TENDER_EXEC_LAW_VAT, 'Возврат НДС'), ])
def __init__(self, *args, **kwargs): super(altaMozoForm, self).__init__(*args, **kwargs) #Esto siempre hay que ponerlo #manejo de mensajes de error self.fields['username'].error_messages = { 'required': 'El nombre de Usuario no es valido!' } self.fields['password'].error_messages = { 'required': 'El password ingresado no es valido!' } self.fields['email'].error_messages = { 'required': 'La direccion de E-mail ingresada no es correcta!' } #formateando los inputs ACTIVO = ((True, 'Activo'), (False, 'Inactivo')) self.fields['is_active'].widget = Select(choices=ACTIVO) self.fields['password'].widget = PasswordInput() #agregando max-length self.fields['numeroDoc'].widget.attrs['maxlength'] = 8
class ManufacturerFilterSet(FilterSet): manufacturer = ModelChoiceFilter( queryset=Manufacturer.objects.all(), widget=Select(attrs={'ng-change': 'filterChanged()'}), empty_label=_("Any Manufacturer"), help_text=_("Restrict product on this manufacturer only"), ) class Meta: model = Product form = FilterForm fields = ['manufacturer'] @classmethod def get_render_context(cls, request, queryset): # create filter set with bound form, to enable the selected option filter_set = cls(data=request.GET) # we only want to show manufacturers for products available in the current list view filter_field = filter_set.filters['manufacturer'].field filter_field.queryset = filter_field.queryset.filter( id__in=queryset.values_list('manufacturer_id')) return dict(filter_set=filter_set)
class CactusJobForm(forms.Form): name = forms.CharField(initial='test') #thornlist = forms.ModelChoiceField(Thornfiles, label='Select Thorn') corecount = forms.CharField(initial=1, label='Core Count') parameterfile = forms.FileField(label='Parmeter File') walltime = forms.ChoiceField(widget=Select(), label='Expected Runtime', \ choices=time_list, initial='2879') pilot = forms.ModelChoiceField(UserResource.objects, label='Select Resource') def __init__(self, user, *args, **kwargs): super(CactusJobForm, self).__init__(*args, **kwargs) self.fields['pilot'].queryset = UserResource.objects.filter(user=user) self.fields['pilot'].error_messages['required'] = 'Please select a Resource or Create a new resource' #self.fields['thornlist'].queryset = Thornfiles.objects.filter(user=user) #self.fields['thornlist'].error_messages['required'] = 'Please select a Thornfile or upload Thornfiles in Manage Thorn List' def save(self, request): job = Job(user=request.user, status="New", name=self.cleaned_data['name']) job.save() for key, value in list(self.cleaned_data.items()): if key in ['name']: continue if key.lower() == 'parameterfile': newdoc = Paramfiles(paramfile=request.FILES['parameterfile'], job=job) newdoc.save() jobinfo = JobInfo(key=key, value=newdoc.id, job=job) jobinfo.save() else: if hasattr(value, 'id'): jobinfo = JobInfo(key=key, value=value.id, job=job) else: jobinfo = JobInfo(key=key, value=value, job=job) jobinfo.save() add_dare_job.delay(job) return job
def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(OrderDeliveryForm, self).__init__(*args, **kwargs) self.fields['scheduled_delivery_date'].widget = DateTimePicker(options=DATEPICKER_OPTIONS) self.fields['delivered_date'].widget = DateTimePicker(options=DATEPICKER_OPTIONS) self.fields['pickup_from'].required = False #self.fields['delivery_cost'].widget = BootstrapTextInput(prepend='$') self.fields['delivery_cost'].initial = 0.0 self.fields['paid'].widget = Select(choices = ((0,"No"), (1, "Yes"))); self.fields['paid'].initial = False #self.fields['delivery_cost'].initial = 0.00 disabled_fields = ['order'] self.fields_to_disable = [] self.fields_to_remove = [] if self.request: if utils.is_user_delivery_group(self.request): # person can modify only certain delivery info data visible_fields = ('scheduled_delivery_date', 'delivered_date', 'comments', 'delivery_person_notes', 'delivery_cost', 'paid') disabled_fields += ['comments', 'paid'] self.fields_to_remove = [f for f in self.fields if f not in visible_fields] for field in self.fields_to_remove: del self.fields[field] elif self.request.user.groups.filter(Q(name="managers") | Q(name="associates")).exists() : disabled_fields.append('delivery_person_notes') disabled_fields.append('delivery_cost') if not self.request.user.has_perm('orders.modify_delivery_fee'): disabled_fields.append('paid') self.fields_to_disable = [f for f in self.fields if f in disabled_fields] for field in self.fields_to_disable: self.fields[field].widget.attrs['disabled'] = 'disabled'
def __init__(self, *args, **kwargs): # Формируем список возможных значений queryset = Terms.objects.filter(vocabulary=self.admin_field.vocabulary) if self.admin_field.lang_depended: queryset = queryset.filter(language=self.language) # Определяем язык language = self.admin_field.lang_depended and self.language or '' # Обращаемся к обработчику по-умолчанию super().__init__(*args, **kwargs) old_widget = self.fields['terms'].widget if self.admin_field.multiple: # Если поле множественного выбора widget = SelectMultiple(old_widget.widget.attrs, queryset) widget_wrapped = SCMSRelatedFieldWidgetWrapper( widget, old_widget.rel, old_widget.admin_site, self.admin_field.vocabulary, language) self.fields['terms'] = ModelMultipleChoiceField( queryset, required=False, widget=widget_wrapped) else: # Если поле одиночного выбора widget = Select(old_widget.widget.attrs, queryset) widget_wrapped = SCMSRelatedFieldWidgetWrapper( widget, old_widget.rel, old_widget.admin_site, self.admin_field.vocabulary, language) self.fields['terms'] = ModelChoiceField(queryset, required=False, widget=widget_wrapped) try: # Определяем значение по умолчанию -- первое в списке значений initial = instance.terms.get_queryset()[0].id except: initial = None self.initial['terms'] = initial self.fields['terms'].initial = initial pass
def get_context_data(self, **kwargs): ctx = super(ElectionDetailView, self).get_context_data(**kwargs) if self.object.voters.count() <= 100: ctx['voters'] = self.object.voters.all().prefetch_related( 'preferences', 'preferences__candidate') ctx['results'] = self.object.results.all()\ .select_related('geneticalgorithmsettings').prefetch_related('winners') choices = [(res.pk, str(res)) for res in ctx['results'].reverse()] choices.append((None, '------')) choices.reverse() ctx['results_choice'] = Select(choices=choices).render( 'results_choice', None) ctx['results_number'] = self.object.results.count() ctx['results_pks'] = ",".join( [str(n) for n in self.object.results.values_list('pk', flat=True)]) ctx['results_p_params'] = "," + ",".join([ str(n) for n in self.object.results.values_list('p_parameter', flat=True) ]) ctx['results_descriptions'] = "No result," + ",".join([ '{}: p = {}'.format(r.get_algorithm_display(), r.p_parameter) for r in self.object.results.all() ]) return ctx
class Meta: model = Course fields = ('course_name', 'course_days', 'start_time', 'end_time', 'instructor') labels = { 'course_name': 'Class name', 'start_time': 'Start time (e.g. 10:00 AM)', 'end_time': 'End time (e.g. 12:00 PM)', 'instructor': 'Instructor (not selecting will be set to ' '\'Not Specified\')' } widgets = { 'course_name': TextInput(attrs={'class': 'form-control mb-2'}), 'start_time': TimeInput(format='%H:%M', attrs={ 'class': 'form-control mb-2', 'type': 'time' }), 'end_time': TimeInput(format='%H:%M', attrs={ 'class': 'form-control mb-2', 'type': 'time' }), 'instructor': Select(attrs={'class': 'form-control mb-2'}) } required = { 'instructor': False, }
class profile_form(forms.ModelForm): class Meta: model = Institutes fields = [ 'name', 'details', 'start_date', 'address', 'city', 'contact', "start_date" ] name = forms.CharField(widget=TextInput(attrs={ "class": "form-control", "rows": "5" })) details = forms.CharField(widget=Textarea(attrs={ "class": "form-control", "rows": "5" })) address = forms.CharField(widget=Textarea( attrs={ "class": "form-control", "rows": "3", "cols": "56" })) contact = forms.IntegerField(widget=NumberInput( attrs={"class": "form-control"})) cities = prepareCityList() city = forms.ChoiceField(widget=Select(attrs={"class": "form-control"}), choices=cities) start_date = forms.DateField(widget=forms.DateInput(attrs={ "class": "form-control", 'type': "date" })) def clean_city(self): city_id = self.cleaned_data['city'] return City(id=city_id)
def __init__(self, *args, **kwargs): user = kwargs.pop("user") super(ProcessingConfigurationForm, self).__init__(*args, **kwargs) self._load_processing_config_fields(user) for choice_uuid, field in self.processing_fields.items(): ftype = field['type'] opts = self.DEFAULT_FIELD_OPTS.copy() opts['label'] = field['label'] if ftype == 'days': opts['min_value'] = 0 self.fields[choice_uuid] = forms.IntegerField(**opts) widget = self.fields[choice_uuid].widget widget.attrs['placeholder'] = _('days') widget.attrs['class'] = 'form-control' continue choices = opts['choices'] = list(self.EMPTY_CHOICES) if ftype == 'boolean': if 'yes_option' in field: choices.append((field['yes_option'], _('Yes'))) if 'no_option' in field: choices.append((field['no_option'], _('No'))) elif ftype in ('chain_choice', 'replace_dict'): choices.extend(field['options']) elif ftype == 'storage_service': choices.append( ('/api/v2/location/default/{}/'.format(field['purpose']), _('Default location'))) for loc in get_storage_locations(purpose=field['purpose']): label = loc['description'] if not label: label = loc['relative_path'] choices.append((loc['resource_uri'], label)) self.fields[choice_uuid] = forms.ChoiceField( widget=Select(attrs={'class': 'form-control'}), **opts)
class Meta: model = ClientRelative exclude = ('client', ) labels = { 'last_name': 'Фамилия', 'first_name': 'Имя', 'part_name': 'Отчество', 'position': 'Должность', 'phone_number': 'Телефонный номер', 'email_v': 'Email', 'relation_degree': 'Степень родства', 'birthday': 'Дата рождения', } widgets = { 'first_name': simpleInput, 'last_name': simpleInput, 'part_name': simpleInput, 'position': simpleInput, 'phone_number': simpleInput, 'email_v': EmailInput(attrs={ 'class': 'form-control', }), 'relation_degree': Select(attrs={ 'class': 'form-control', }, choices=RELATION_DEGREE_CHOISES), 'birthday': simpleDate, }
def __init__(self, *args, **kwargs): super(PopulatedForm, self).__init__(*args, **kwargs) if request.method in ['GET', 'POST']: for key in request.GET: try: field = self.fields[key] field.required = False if isinstance(field, forms.models.ModelChoiceField): field.empty_label = None related_model_name = ( field.queryset.model._meta.model_name.title()) cls = getattr(models, related_model_name, None) if cls: object_id = request.GET[key] field.widget = (Select( attrs={'disabled': 'disabled'})) field.queryset = (cls.objects.filter( id=object_id)) else: field.widget.attrs['readonly'] = True field.widget.attrs['disabled'] = 'disabled' except KeyError: # Ignore unexpected parameters pass
def render(self, name, value, attrs=None, renderer=None): try: year_val, month_val = value.year, value.month except AttributeError: year_val = month_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [ int(v) for v in match.groups() ] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name month_choices = MONTHS.items() # if not (self.required and value): #MONTHS[0] = self.month_none_value[1] # month_choices.append(self.none_value) #month_choices = MONTHS.items() month_choices = sorted(month_choices) #myfield = self.month_field % id_ # , extra_attrs={id: myfield} local_attrs = self.build_attrs(base_attrs={}) local_attrs['id'] = self.month_field % id_ s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) year_choices = [(i, i) for i in self.years] # if not (self.required and value): # year_choices.insert(0, self.year_none_value) local_attrs['id'] = self.year_field % id_ s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(select_html) return mark_safe(u'\n'.join(output))
def __init__(self, attrs=None): freqOptions = [(DAILY, _("Daily")), (WEEKLY, _("Weekly")), (MONTHLY, _("Monthly")), (YEARLY, _("Yearly"))] ordOptions1 = [(1, toTheOrdinal(1)), (2, toTheOrdinal(2)), (3, toTheOrdinal(3)), (4, toTheOrdinal(4)), (5, toTheOrdinal(5)), (-1, toTheOrdinal(-1)), (EVERY_DAY, _("Every")), (SAME_DAY, _("The Same"))] ordOptions2 = [(None, ""), (1, toTheOrdinal(1)), (2, toTheOrdinal(2)), (3, toTheOrdinal(3)), (4, toTheOrdinal(4)), (5, toTheOrdinal(5)), (-1, toTheOrdinal(-1))] dayOptions1 = enumerate(WEEKDAY_ABBRS) dayOptions2 = [(None, "")] + list(enumerate(WEEKDAY_NAMES)) dayOptions3 = list(enumerate(WEEKDAY_NAMES)) +\ [(DAY_OF_MONTH, _("Day of the month"))] monthOptions = enumerate(MONTH_ABBRS[1:], 1) numAttrs = {'min': 1, 'max': 366} disableAttrs = {'disabled': True} if attrs: numAttrs.update(attrs) disableAttrs.update(attrs) widgets = [ AdminDateInput(attrs=attrs), Select(attrs=attrs, choices=freqOptions), #1 NumberInput(attrs=numAttrs), CheckboxSelectMultiple(attrs=attrs, choices=dayOptions1), NumberInput(attrs=numAttrs), AdminDateInput(attrs=attrs), #5 Select(attrs=attrs, choices=ordOptions1), Select(attrs=attrs, choices=dayOptions3), Select(attrs=disableAttrs, choices=ordOptions2), Select(attrs=disableAttrs, choices=dayOptions2), Select(attrs=disableAttrs, choices=ordOptions2), #10 Select(attrs=disableAttrs, choices=dayOptions2), CheckboxSelectMultiple(attrs=attrs, choices=monthOptions) ] super().__init__(widgets, attrs)
def render(self, name, value, attrs=None): try: year_val, month_val = value.year, value.month except AttributeError: year_val = month_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name month_choices = MONTHS.items() if not (self.required and value): month_choices.append(self.none_value) month_choices.sort() build_attrs = { 'id': self.month_field % id_ } local_attrs = self.build_attrs(build_attrs) s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) year_choices = [(i, i) for i in self.years] if not (self.required and value): year_choices.insert(0, self.none_value) local_attrs['id'] = self.year_field % id_ s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(select_html) # Hidden widget for custom datefield s = HiddenInput() output.append(s.render('date_mozillian', None)) return mark_safe(u'\n'.join(output))
def __init__(self, attrs=None): freqOptions = [(3, "Daily"), (2, "Weekly"), (1, "Monthly"), (0, "Yearly")] ordOptions1 = [(1, "The First"), (2, "The Second"), (3, "The Third"), (4, "The Fourth"), (5, "The Fifth"), (-1, "The Last"), (_EveryDay, "Every"), (_SameDay, "The Same")] ordOptions2 = [(None, ""), (1, "The First"), (2, "The Second"), (3, "The Third"), (4, "The Fourth"), (5, "The Fifth"), (-1, "The Last")] dayOptions1 = enumerate(calendar.day_abbr) dayOptions2 = [(None, "")] + list(enumerate(calendar.day_name)) dayOptions3 = list(enumerate(calendar.day_name)) +\ [(_DayOfMonth, "Day of the month")] monthOptions = enumerate(calendar.month_abbr[1:], 1) numAttrs = {'min': 1, 'max': 366} disableAttrs = {'disabled': True} if attrs: numAttrs.update(attrs) disableAttrs.update(attrs) widgets = [ AdminDateInput(attrs=attrs), Select(attrs=attrs, choices=freqOptions), #1 NumberInput(attrs=numAttrs), CheckboxSelectMultiple(attrs=attrs, choices=dayOptions1), NumberInput(attrs=numAttrs), AdminDateInput(attrs=attrs), #5 Select(attrs=attrs, choices=ordOptions1), Select(attrs=attrs, choices=dayOptions3), Select(attrs=disableAttrs, choices=ordOptions2), Select(attrs=disableAttrs, choices=dayOptions2), Select(attrs=disableAttrs, choices=ordOptions2), #10 Select(attrs=disableAttrs, choices=dayOptions2), CheckboxSelectMultiple(attrs=attrs, choices=monthOptions) ] super().__init__(widgets, attrs)
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.get_year(), value.get_month(empty_allowed=True), value.get_day(empty_allowed=True) except AttributeError: year_val, month_val, day_val = None, None, None output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name local_attrs = self.build_attrs(id=self.year_field % id_) year_choices = [(i, i) for i in self.years] year_choices.reverse() if not self.required: year_choices = [(0,'(year)')] + year_choices s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(select_html) month_choices = list(MONTHS.items()) month_choices.append(self.none_value) month_choices.sort() local_attrs['id'] = self.month_field % id_ s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) day_choices = [(i, i) for i in range(1, 32)] day_choices.insert(0, self.none_value) local_attrs['id'] = self.day_field % id_ s = Select(choices=day_choices) select_html = s.render(self.day_field % name, day_val, local_attrs) output.append(select_html) return mark_safe(u'\n'.join(output))
def 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, string_types): 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()) if not (self.required and value): month_choices.append(self.none_value) month_choices.sort() local_attrs = self.build_attrs(self.attrs) local_attrs['id'] = self.month_field % id_ s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) year_choices = [(i, i) for i in self.years] if not (self.required and value): year_choices.insert(0, self.none_value) local_attrs['id'] = self.year_field % id_ s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(select_html) return mark_safe(u'\n'.join(output))
def render(self, name, value, attrs=None): try: month_val, day_val = value.year, value.month, value.day except AttributeError: month_val = day_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: month_val, day_val = [int(v) for v in match.groups()] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name day_choices = [(i, i) for i in range(1, 32)] if not (self.required and value): day_choices.insert(0, self.none_value) local_attrs = self.build_attrs(id=self.day_field % id_) s = Select(choices=day_choices) select_html = s.render(self.day_field % name, day_val, local_attrs) output.append(select_html) month_choices = MONTHS.items() if not (self.required and value): month_choices.append(self.none_value) month_choices.sort() local_attrs['id'] = self.month_field % id_ s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) return mark_safe(u'\n'.join(output))
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))
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, str): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name year_choices = [(0, 'YYYY'), ] + [(i, i) for i in reversed(self.years)] local_attrs = self.build_attrs({"id": self.year_field % id_, "class": "select"}) s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append('<div class="col-xl-8">%s</div>' % select_html) month_choices = [(0, 'MM'), ] + list(MONTHS.items()) local_attrs['id'] = self.month_field % id_ s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append('<div class="col-xl-8">%s</div>' % select_html) day_choices = [(0, 'DD'), ] + [(i, i) for i in range(1, 32)] local_attrs['id'] = self.day_field % id_ s = Select(choices=day_choices) select_html = s.render(self.day_field % name, day_val, local_attrs) output.append('<div class="col-xl-8">%s</div>' % select_html) return mark_safe(u'\n'.join(output))
def render_option(self, selected_choices, option_value, option_label): """Render a single option (brother) in the format 'First Last ... badge' (e.g., 'George Burdell ... 0').""" new_label = ('%s ... %d' % (option_label, option_value) if option_value > 0 else option_label) return Select.render_option(self, selected_choices, option_value, new_label)
def __init__(self, attrs=None): choices = (('1', ('---')), ('2', ugettext_lazy('yes')), ('3', ugettext_lazy('no'))) Select.__init__(self, attrs, choices)
def __init__(self, jquery=None, attrs=None, choices=(), buit=None): self.jquery = jquery if jquery else u'' self.buit = buit if buit else False Select.__init__(self, attrs=attrs, choices=choices)
class ArticleForm(ModelForm): semester = ChoiceField( choices=Article.SEMESTER_CHOICES, widget=Select( attrs={ 'id': 'article_semester', 'class': 'form-control custom-select select-fix-height', 'name': 'semester', }), required=False, ) year = ChoiceField( choices=Article.YEAR_CHOICES, widget=Select( attrs={ 'id': 'article_year', 'class': 'form-control custom-select select-fix-height', 'name': 'year', }), required=False, initial=Article.current_year) section = ChoiceField( widget=Select( attrs={ 'id': 'article_course_section', 'class': 'form-control custom-select select-fix-height', 'name': 'section', }), required=False, ) course = ModelChoiceField( queryset=Course.objects.all(), widget=Select( attrs={ 'id': 'article_course', 'class': 'form-control select-fix-height', 'name': 'course', }), required=False, empty_label="Select a course") class Meta: model = Article fields = ( 'course', 'section', 'description', 'semester', 'year', 'is_public', 'title', ) def __init__(self, *args, **kwargs): super(ArticleForm, self).__init__(*args, **kwargs) self.fields['title'].widget = TextInput( attrs={ 'id': 'article_title', 'class': 'form-control', 'name': 'title', 'autocomplete': 'new-password' }) self.fields['description'].widget = Textarea( attrs={ 'id': 'article_description', 'class': 'form-control', 'name': 'description', }) section_choices = [] if 'course' in self.data and self.data['course']: section_choices += BLANK_CHOICE_DASH course_id = self.data.get('course') course = Course.objects.get(pk=course_id) for section in course.sections: section_choices.append((section, "{:02d}".format(section))) elif self.instance.pk and self.instance.course: section_choices += BLANK_CHOICE_DASH course = self.instance.course for section in course.sections: section_choices.append((section, "{:02d}".format(section))) elif not all(('course' in self.data, self.instance.course)): self.fields['section'].disabled = True self.fields['section'].choices = section_choices def clean_year(self): year = self.cleaned_data.get('year') if year: return year return None def clean_section(self): section = self.cleaned_data.get('section') if section: return section return None
ArticleMediaFormSet = inlineformset_factory( Article, ArticleMedia, formset=BaseArticleMediaFormSet, fields=('article_media', 'article_type'), extra=1, widgets={ 'article_media': FileInput(attrs={ 'class': 'custom-file', 'multiple': True }), 'article_type': Select(attrs={'class': 'form-control select-fix-height'}) }) class ArticleForm(ModelForm): semester = ChoiceField( choices=Article.SEMESTER_CHOICES, widget=Select( attrs={ 'id': 'article_semester', 'class': 'form-control custom-select select-fix-height', 'name': 'semester', }), required=False, )
class Meta: model = Intake fields = [ 'how_can_we_help', 'how_can_we_help_other', 'how_can_we_help_tag', 'how_did_you_hear', 'how_did_you_hear_other', 'do_you_own_a_biz', 'do_you_own_a_biz_other', 'has_telephone', 'telephone', 'telephone_time', 'government_benefits', 'other_government_benefit', 'identities', 'date_of_birth', 'has_business_idea', 'naics_depth_one', 'naics_depth_two', 'naics_depth_three', 'naics_depth_four', 'naics_depth_five', 'has_signed_privacy_and_terms', 'has_signed_confidentiality_agreement', 'has_signed_collection_and_use_of_information', 'has_signed_with_name', 'has_signed_on_date', ] labels = { 'how_can_we_help_tag': _('Which program are you interested in?'), # 'industry': _('Industry'), # 'image': _('Image'), } widgets = { 'how_can_we_help': Select(attrs={ 'class': u'form-control input-lg', }), 'how_can_we_help_other': TextInput( attrs={ 'class': u'form-control input-lg', # 'placeholder': _('Enter name.') }), 'how_can_we_help_tag': Select( attrs={ 'class': u'form-control input-lg', # 'placeholder': _('Enter name.') }), 'how_did_you_hear': Select(attrs={ 'class': u'form-control input-lg', }), 'how_did_you_hear_other': TextInput( attrs={ 'class': u'form-control input-lg', # 'placeholder': _('Enter name.') }), 'do_you_own_a_biz': Select(attrs={ 'class': u'form-control input-lg', }), 'do_you_own_a_biz_other': TextInput( attrs={ 'class': u'form-control input-lg', # 'placeholder': _('Enter name.') }), 'has_telephone': Select(attrs={ 'class': u'form-control input-lg', }), 'telephone': TextInput( attrs={ 'class': u'form-control input-lg', # 'placeholder': _('Enter name.') }), 'telephone_time': Select(attrs={ 'class': u'form-control input-lg', }), 'government_benefits': CheckboxSelectMultiple(), 'other_government_benefit': TextInput( attrs={ 'class': u'form-control input-lg', # 'placeholder': _('Enter name.') }), 'identities': CheckboxSelectMultiple(), 'date_of_birth': TextInput(attrs={ 'class': u'form-control input-lg', }), 'naics_depth_one': Select(attrs={ 'class': u'form-control input-lg', }), 'naics_depth_two': Select(attrs={ 'class': u'form-control input-lg', }), 'naics_depth_three': Select(attrs={ 'class': u'form-control input-lg', }), 'naics_depth_four': Select(attrs={ 'class': u'form-control input-lg', }), 'naics_depth_five': Select(attrs={ 'class': u'form-control input-lg', }), 'has_signed_with_name': TextInput( attrs={ 'class': u'form-control input-lg', # 'placeholder': _('Enter name.') }), 'has_signed_on_date': TextInput( attrs={ 'class': u'form-control input-lg', # 'placeholder': _('Enter name.') }), }
def __init__(self, attrs=None, *args, **kwargs): widgets = (Textarea(attrs), Select(attrs, choices=settings.LANGUAGES)) super(TranslatableTextField, self).__init__(widgets, attrs)
def __init__(self, attrs=None): choices = ((u'1', ugettext(u'Indifférent')), (u'2', ugettext(u'Oui')), (u'3', ugettext(u'Non'))) Select.__init__(self, attrs, choices)
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, basestring): 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 self.twelve_hr and 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_) select_html = Select(choices=hour_choices).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) if self.seconds: 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) else: output.append( '<input type="hidden" id="id_%s" name="%s" value="00">' % (self.second_field % name, self.second_field % name)) 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))
def render(self): se = Select(choices=self.options) name = "stateselect" return se.render("stateselect", self.val, attrs={"id": "id-state-select"})
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> <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
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 __init__(self, *args, **kwargs): departments = kwargs.pop('departments', []) widgets = (TextInput(), Select(choices=departments)) super(CandidateWidget, self).__init__(widgets, *args, **kwargs)
def __init__(self, *args, **kwargs): widgets = (NumberInput(), Select(choices=self.UNIT_CHOICES)) super(DistanceSelect, self).__init__(widgets=widgets, *args, **kwargs)
We recommend [**WebFaction**][1] for OSQA hosting. For \ under $10/month their reliable servers get the job done. See our \ [**step-by-step setup guide**](http://wiki.osqa.net/display/docs/Installing+OSQA+on+WebFaction). [1]: http://www.webfaction.com?affiliate=osqa [2]: /m/default/media/images/webfaction.png""", SIDEBAR_SET, dict(label="Upper Block Content", help_text=" The upper sidebar block. ", widget=Textarea(attrs={'rows': '10'}))) SIDEBAR_UPPER_RENDER_MODE = Setting( 'SIDEBAR_UPPER_RENDER_MODE', 'markdown', SIDEBAR_SET, dict(label=_("Upper block rendering mode"), help_text=_("How to render your upper block code."), widget=Select(choices=RENDER_CHOICES), required=False)) SIDEBAR_LOWER_SHOW = Setting( 'SIDEBAR_LOWER_SHOW', True, SIDEBAR_SET, dict( label="Show Lower Block", help_text="Check if your pages should display the lower sidebar block.", required=False)) SIDEBAR_LOWER_DONT_WRAP = Setting( 'SIDEBAR_LOWER_DONT_WRAP', False, SIDEBAR_SET, dict(label="Don't Wrap Lower Block", help_text="Don't wrap lower block with the standard style.", required=False))
def render_options(self, choices, selected_choices): """Render all options in the set of choices.""" return Select.render_options(self, choices, selected_choices)