Django forms select

Django forms select DEFAULT

Python django.forms.Select() Examples

The following are 30 code examples for showing how to use django.forms.Select(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.forms, or try the search function .

Example 1

def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(KoScheduleForm, self).__init__(*args, **kwargs) # if hasattr(self.request, "project") and self.request.project is not None: # xform = XForm.objects.filter( # Q(user=self.request.user) | Q(fieldsightformlibrary__is_global=True) | # Q(fieldsightformlibrary__project=self.request.project) | # Q(fieldsightformlibrary__organization=self.request.organization)) if hasattr(self.request, "organization") and self.request.organization is not None: xform = XForm.objects.filter( Q(user=self.request.user) | Q(user__user_profile__organization=self.request.organization), deleted_xform=None) else: xform = XForm.objects.filter( Q(user=self.request.user) | Q(fieldsightformlibrary__is_global=True), deleted_xform=None) self.fields['form'].choices = [(obj.id, obj.title) for obj in xform] self.fields['form'].empty_label = None self.fields['form'].label = "Select Form"

Example 2

def __init__(self, *args, **kwargs): """ We change the widget of the fields We get the original form, register all repositories, create the list of protocols. If a repo exists, we check that its protocol will be in the list. Otherwise the protocol of a repo with a currently not registered protocol would be overwritten. """ super().__init__(*args, **kwargs) # Protocol # Get the list with names of protocols protocol_registry.load() choices = [(key, str(value)) for key, value in protocol_registry.dct.items()] # If the repo uses a protocol not in the list, we add this value, otherwise it is overriden on saving if self.instance.protocol: if self.instance.protocol not in protocol_registry.dct.keys(): choices += [(self.instance.protocol,self.instance.protocol)] # Sort and populate the form choices = sorted(choices, key=lambda protocol: protocol[1].lower(),) self.fields['protocol'].widget = forms.Select(choices=choices)

Example 3

def __init__(self, *args, **kwargs): from .election_specific import shorten_post_label election = kwargs.pop('election') super(AddCandidacyPickPostForm, self).__init__(*args, **kwargs) self.fields['post'] = forms.ChoiceField( label=_('Post in %s') % election.name, choices=[('', '')] + sorted( [ (post.extra.slug, shorten_post_label(post.label)) for post in Post.objects.select_related('extra').filter(extra__elections=election) ], key=lambda t: t[1] ), widget=forms.Select(attrs={'class': 'post-select'}), )

Example 4

def __init__(self, attrs=None): self.time_class = "timepicker" if not attrs: attrs = {} if "time_class" in attrs: self.time_class = attrs.pop("time_class") if "class" not in attrs: attrs["class"] = "time" widgets = ( forms.Select( attrs=attrs, choices=[(i + 1, "%02d" % (i + 1)) for i in range(0, 12)] ), forms.Select( attrs=attrs, choices=[(i, "%02d" % i) for i in range(00, 60, 15)] ), forms.Select(attrs=attrs, choices=[("AM", _("AM")), ("PM", _("PM"))]), ) super(TimeWidget, self).__init__(widgets, attrs)

Example 5

def set_fields(cls, category, products): choices = [] if not category.required: choices.append((0, "---")) for product in products: choice_text = "%s -- $%d each" % (product.name, product.price) choices.append((product.id, choice_text)) cls.base_fields[cls.CHOICE_FIELD] = forms.TypedChoiceField( label=category.name, widget=forms.Select, choices=choices, initial=0, empty_value=0, coerce=int, ) cls.base_fields[cls.QUANTITY_FIELD] = forms.IntegerField( label="Quantity", # TODO: internationalise min_value=0, max_value=500, # Issue #19. We should figure out real limit. )

Example 6

def staff_products_form_factory(user): ''' Creates a StaffProductsForm that restricts the available products to those that are available to a user. ''' products = inventory.Product.objects.all() products = ProductController.available_products(user, products=products) product_ids = [product.id for product in products] product_set = inventory.Product.objects.filter(id__in=product_ids) class StaffProductsForm(forms.Form): ''' Form for allowing staff to add an item to a user's cart. ''' product = forms.ModelChoiceField( widget=forms.Select, queryset=product_set, ) quantity = forms.IntegerField( min_value=0, ) return StaffProductsForm

Example 7

def render(self, name, value, attrs=None): if not self._isiterable(value): value = [value] if len(value) <= 1: # delegate to main widget (Select, etc...) if not multiple values value = value[0] if value else '' return super(BaseCSVWidget, self).render(name, value, attrs) # if we have multiple values, we need to force render as a text input # (otherwise, the additional values are lost) surrogate = forms.TextInput() value = [force_text(format_value(surrogate, v)) for v in value] value = ','.join(list(value)) return surrogate.render(name, value, attrs)

Example 8

def __init__(self, *args, **kwargs): kwargs.setdefault('label_suffix', '') super(PoliticianForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): if isinstance(field.widget, forms.TextInput) or isinstance(field.widget, forms.Select) or isinstance(field.widget, forms.EmailInput): field.widget.attrs.update({ 'class': 'form-control' }) if field_name == 'party': field.choices = [('', '---------')] field.choices += [ (p.id, p.name) for p in Party.objects.order_by('name') ] if isinstance(field.widget, forms.Textarea): field.widget.attrs.update({ 'class': 'form-control', 'rows': 2, })

Example 9

def prepare_select(self, field): field_attrs = field.build_field_attrs() widget_attrs = field.build_widget_attrs() field_attrs.update({ 'widget': forms.Select(attrs=widget_attrs) }) if field.choice_values: choice_list = field.get_choices() if not field.required: choice_list.insert(0, ('', field.placeholder_text or _('Please select an option'))) field_attrs.update({ 'choices': choice_list }) return forms.ChoiceField(**field_attrs)

Example 10

def __init__(self, *args, **kwargs): self.protege = kwargs.pop("protege") super().__init__(*args, **kwargs) meeting = kwargs.get("instance") choices = [("", _("--- Selecciona ---"))] choices.extend(meeting.mentor.get_meeting_formats()) self.fields["format"].widget = Select(choices=choices) self.fields["format"].required = True self.fields["format"].label = _("Formato") self.fields["message"].required = True self.fields["message"].label = _("Mensaje") self.fields["message"].help_text = _( "En este mensaje, explica de que quieres hablar en la reunión, por qué escogiste a esta persona. Trata de dejarle saber al mentor los temas que quieres hablar durante la reunión. Piensa que el mentor se tiene que preparar y tu debes estar preparado antes de la reunión. Este mensaje debe ayudar a ambos a saber que esperar de la reunión." )

Example 11

def __init__(self, *args, **kwargs): super(NoteForm, self).__init__(*args, **kwargs) note = kwargs['instance'] self.fields['sender'] = forms.ChoiceField( label=_('From'), choices=note.get_sender_choices(), widget=forms.Select(attrs={'class': 'span12'}) ) self.fields['body'].widget = AutocompleteTextarea( rows=20, choices=Template.templates() ) if note.order: url = reverse('notes-render_template', args=[note.order.pk]) self.fields['body'].widget.attrs['data-url'] = url

Example 12

def __init__(self): widgets = ( forms.Textarea(attrs={'cols': 70, 'rows': 20}), forms.Select(), forms.CheckboxInput(), ) super(MarkupContentWidget, self).__init__(widgets)

Example 13

def __init__(self, *args, **kwargs): widgets = [forms.Select(), forms.TextInput(attrs={'size': 8, 'maxlength': 8})] kwargs['widgets'] = widgets super(SupervisorWidget, self).__init__(*args, **kwargs)

Example 14

def __init__(self, *args, **kwargs): widgets = [forms.Select() for c in CATEGORY_CHOICES] kwargs['widgets'] = widgets super(AccountsWidget, self).__init__(*args, **kwargs)

Example 15

def __init__(self, *args, **kwargs): super(GravityLogCreateForm, self).__init__(*args, **kwargs) for this_field in self.fields: self.fields[this_field].widget.attrs['class'] = "form-control" self.fields['device'] = forms.ChoiceField(required=True, choices=self.get_device_choices(), widget=forms.Select(attrs={'class': 'form-control', 'data-toggle': 'select'}))

Example 16

def __init__(self, *args, **kwargs): super(SensorAttachForm, self).__init__(*args, **kwargs) for this_field in self.fields: self.fields[this_field].widget.attrs['class'] = "form-control" self.fields['sensor'] = forms.ChoiceField(required=True, choices=self.get_sensor_choices(), widget=forms.Select(attrs={'class': 'form-control', 'data-toggle': 'select'})) self.fields['temp_controller'] = forms.ChoiceField(required=True, choices=self.get_controller_choices(), widget=forms.Select(attrs={'class': 'form-control', 'data-toggle': 'select'}))

Example 17

def __init__(self, *args, **kwargs): super(TiltCreateForm, self).__init__(*args, **kwargs) for this_field in self.fields: self.fields[this_field].widget.attrs['class'] = "form-control" self.fields['tiltbridge'] = forms.ChoiceField(required=False, choices=self.get_tiltbridge_choices(), widget=forms.Select(attrs={'class': 'form-control', 'data-toggle': 'select'}))

Example 18

def __init__(self, *args, **kwargs): super(TempControlForm, self).__init__(*args, **kwargs) # for this_field in self.fields: # self.fields[this_field].widget.attrs['class'] = "form-control" self.fields['profile'] = forms.ChoiceField(required=False, choices=self.get_profile_choices(), widget=forms.Select(attrs={'class': 'form-control'})) # Check that the Start At format is valid, and if it is, replace it with a datetime delta object

Example 19

def __init__(self, *args, **kwargs): super(BeerCreateForm, self).__init__(*args, **kwargs) for this_field in self.fields: self.fields[this_field].widget.attrs['class'] = "form-control" self.fields['device'] = forms.ChoiceField(required=True, choices=self.get_device_choices(), widget=forms.Select(attrs={'class': 'form-control', 'data-toggle': 'select'}))

Example 20

def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["resource"].widget = forms.Select( choices=self.instance.get_resource_choices() )

Example 21

def __init__(self, *args, **kwargs): """ Letter of Declaration Get the list of user friendly names of the generating functions. We need them as tuple for djangos choices """ super().__init__(*args, **kwargs) choices = sorted([(value, value) for value in REGISTERED_DECLARATION_FUNCTIONS], key=lambda item: item[1]) self.fields['function_key'].widget = forms.Select(choices=choices)

Example 22

def __init__(self, *args, **kwargs): """Administrator contant form initialization. Administrator choice need to be here, as new Django release tries to import this form during migrations, even if user table is not available. """ super(AdministratorContactForm, self).__init__(*args, **kwargs) self.administrator = forms.Select( choices=get_administrators_emails().items(), )

Example 23

def render(self, name, value, attrs=None): self.choices = self.form_instance.fields['next_service'].choices s = super(forms.Select, self).render(name, value, attrs) h="<BR/>" ind= "-> {}<BR/>" for next in self.form_instance.instance.next_chain(): h = h+ ind.format( str(next)) ind = "--" + ind return mark_safe(s+ h )

Example 24

def __init__(self, *args, **kwargs): subject = kwargs.pop('subject', None) contacts = kwargs.pop('contacts', None) super(ContactForm, self).__init__(*args, **kwargs) if subject: self.fields['subject'].initial = subject if contacts: contact_choices = [] for contact in contacts: contact_choices.append([contact.email, '{name}, {role}'.format(name=contact.name, role=contact.role)]) self.fields['recipient'].widget = forms.Select(choices=contact_choices)

Example 25

def __init__(self, *args, **kwargs): settings = kwargs.pop('settings', None) super(GeneratedPluginSettingForm, self).__init__(*args, **kwargs) for field in settings: object = field['object'] if field['types'] == 'char': self.fields[field['name']] = forms.CharField(widget=forms.TextInput(), required=False) elif field['types'] == 'rich-text' or field['types'] == 'text' or field['types'] == 'Text': self.fields[field['name']] = forms.CharField(widget=forms.Textarea, required=False) elif field['types'] == 'json': self.fields[field['name']] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=field['choices'], required=False) elif field['types'] == 'number': self.fields[field['name']] = forms.CharField(widget=forms.TextInput(attrs={'type': 'number'})) elif field['types'] == 'select': self.fields[field['name']] = forms.CharField(widget=forms.Select(choices=field['choices'])) elif field['types'] == 'date': self.fields[field['name']] = forms.CharField( widget=forms.DateInput(attrs={'class': 'datepicker'})) elif field['types'] == 'boolean': self.fields[field['name']] = forms.BooleanField( widget=forms.CheckboxInput(attrs={'is_checkbox': True}), required=False) self.fields[field['name']].initial = object.processed_value self.fields[field['name']].help_text = object.setting.description

Example 26

def __init__(self, *args, **kwargs): settings = kwargs.pop('settings', None) super(GeneratedSettingForm, self).__init__(*args, **kwargs) for field in settings: object = field['object'] if object.setting.types == 'char': self.fields[field['name']] = forms.CharField(widget=forms.TextInput(), required=False) elif object.setting.types == 'rich-text' or object.setting.types == 'text': self.fields[field['name']] = forms.CharField(widget=forms.Textarea, required=False) elif object.setting.types == 'json': self.fields[field['name']] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=field['choices'], required=False) elif object.setting.types == 'number': self.fields[field['name']] = forms.CharField(widget=forms.TextInput(attrs={'type': 'number'})) elif object.setting.types == 'select': self.fields[field['name']] = forms.CharField(widget=forms.Select(choices=field['choices'])) elif object.setting.types == 'date': self.fields[field['name']] = forms.CharField( widget=forms.DateInput(attrs={'class': 'datepicker'})) elif object.setting.types == 'boolean': self.fields[field['name']] = forms.BooleanField( widget=forms.CheckboxInput(attrs={'is_checkbox': True}), required=False) self.fields[field['name']].label = object.setting.pretty_name self.fields[field['name']].initial = object.processed_value self.fields[field['name']].help_text = object.setting.description

Example 27

def __init__(self, *args, **kwargs): if 'config_entity_choices' in kwargs: config_entity_choices = kwargs.pop('config_entity_choices') else: config_entity_choices = [] super(UserGroupsForm, self).__init__(*args, **kwargs) self.fields['config_entity'] = forms.ChoiceField( choices=config_entity_choices, widget=forms.Select(attrs={'class': 'form-control config-entity-select'}) )

Example 28

def __init__(self, *args, **kwargs): initial_role = None role_choices = [] if 'initial_role' in kwargs: initial_role = kwargs.pop('initial_role') if 'role_choices' in kwargs: role_choices = kwargs.pop('role_choices') super(UserForm, self).__init__(*args, **kwargs) self.fields['role'] = forms.ChoiceField(choices=role_choices, widget=forms.Select(attrs={'class': 'form-control'})) if initial_role: self.fields['role'].initial = initial_role

Example 29

def __init__(self, *args, **kwargs): election = kwargs.pop('election') post = kwargs.pop('post') super(AddCandidacyPickPartyForm, self).__init__(*args, **kwargs) party_set = PartySet.objects.get(postextra__slug=post) self.fields['party'] = \ forms.ChoiceField( label=_("Party in {election}").format( election=election.name, ), choices=party_set.party_choices(), required=False, widget=forms.Select( attrs={ 'class': 'party-select party-select-' + election.slug } ), ) if election.party_lists_in_use: # Then add a field to enter the position on the party list # as an integer: self.fields['party_list_position'] = forms.IntegerField( label=_("Position in party list ('1' for first, '2' for second, etc.)"), min_value=1, required=False, widget=forms.NumberInput( attrs={ 'class': 'party-position party-position-' + election.slug } ) )

Example 30

def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["view"].widget = forms.Select(choices=url_choices())
Sours: https://www.programcreek.com/python/example/60824/django.forms.Select

django.forms.Select

Here are the examples of the python api django.forms.Select taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

Example 51

View license def __init__(self, *args, **kwargs): super(QueryServerForm, self).__init__(*args, **kwargs) if conf.QUERY_SERVERS: servers = ((server, server) for server in conf.QUERY_SERVERS.keys()) else: servers = (('default', 'default'),) self.fields['server'].widget = forms.Select(choices=servers)

Example 52

View license def set_dropdown_widgets(self, variable_type=None, variable_name=None, speciation=None): cv_var_type_choices = _get_cv_dropdown_widget_items(self.cv_variable_types, variable_type) self.fields['variable_type'].widget = forms.Select(choices=cv_var_type_choices) cv_var_name_choices = _get_cv_dropdown_widget_items(self.cv_variable_names, variable_name) self.fields['variable_name'].widget = forms.Select(choices=cv_var_name_choices) cv_speciation_choices = _get_cv_dropdown_widget_items(self.cv_speciations, speciation) self.fields['speciation'].widget = forms.Select(choices=cv_speciation_choices)

Example 53

View license def __init__(self, *args, **kwargs): coordinator = kwargs['coordinator'] del kwargs['coordinator'] super(DataInputForm, self).__init__(*args, **kwargs) self.fields['dataset'].queryset = Dataset.objects.filter(coordinator=coordinator) if coordinator.workflow: self.fields['name'].widget = forms.Select(choices=((param, param) for param in set(coordinator.workflow.find_parameters())))

Example 54

View license def __init__(self, *args, **kwargs): if 'initial' not in kwargs or not kwargs.get('initial', False): kwargs['initial'] = {} kwargs['initial']['app_config'] = self.default_appconfig if 'data' in kwargs and kwargs['data'] is not None: kwargs['data']['1-app_config'] = self.default_appconfig super(PostWizardForm, self).__init__(*args, **kwargs) self.fields['app_config'].widget = forms.Select( attrs=self.fields['app_config'].widget.attrs, choices=self.fields['app_config'].widget.choices, ) self.fields['app_config'].widget.attrs['disabled'] = True

Example 55

View license def set_dropdown_widgets(self, site_type=None, elevation_datum=None): cv_site_type_choices = _get_cv_dropdown_widget_items(self.cv_site_types, site_type) self.fields['site_type'].widget = forms.Select(choices=cv_site_type_choices) cv_e_datum_choices = _get_cv_dropdown_widget_items(self.cv_elevation_datums, elevation_datum) self.fields['elevation_datum'].widget = forms.Select(choices=cv_e_datum_choices)

Example 56

View license def __init__(self, *args, **kw): conversation_types = kw.pop('conversation_types') super(ConversationSearchForm, self).__init__(*args, **kw) self.fields['conversation_type'] = forms.ChoiceField( required=False, choices=([('', 'Type ...')] + conversation_types), widget=forms.Select(attrs={'class': 'input-small'}))

Example 57

View license def __init__(self, *args, **kwargs): super(NodeSettingsForm, self).__init__(*args, **kwargs) # add helptexts to radioselect labels for visibility field NODE_VISIBILITY_CHOICES_HELPTEXT = [(i, mark_safe(u"%s<br /><small class=\"helptext\">%s</small>" % (j, k))) for i, j, k in const.NODE_VISIBILITY] self.fields['visibility'].choices = NODE_VISIBILITY_CHOICES_HELPTEXT self.fields['batch_add_users_role'] = forms.CharField(widget=forms.Select(choices=const.NODE_USER_ROLES), required=False) self.fields['batch_add_users_emails'] = forms.CharField(widget=forms.Textarea, required=False)

Example 58

View license def formfield(self, form_class=forms.CharField, **kwargs): "Returns a django.newforms.Field instance for this database Field." defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} if self.choices: defaults['widget'] = forms.Select(choices=self.get_choices(include_blank=self.blank or not (self.has_default() or 'initial' in kwargs))) if self.has_default(): defaults['initial'] = self.get_default() defaults.update(kwargs) return form_class(**defaults)

Example 59

View license def __init__(self, *args, **kwargs): self.protege = kwargs.pop('protege') super(MeetingUpdateForm, self).__init__(*args, **kwargs) meeting = kwargs.get('instance') choices = [('', _('--- Selecciona ---'))] choices.extend(meeting.mentor.get_meeting_formats()) self.fields['format'].widget = Select(choices=choices) self.fields['format'].required = True self.fields['format'].label = _('Formato') self.fields['message'].required = True self.fields['message'].label = _('Mensaje') self.fields['message'].help_text = _(u'En este mensaje, explica de que quieres hablar en la reunión, por qué escogiste a esta persona. Trata de dejarle saber al mentor los temas que quieres hablar durante la reunión. Piensa que el mentor se tiene que preparar y tu debes estar preparado antes de la reunión. Este mensaje debe ayudar a ambos a saber que esperar de la reunión.')

Example 60

View license def set_dropdown_widgets(self, current_sample_medium=None, current_units_type=None, current_agg_statistics=None, current_status=None): cv_sample_medium_choices = _get_cv_dropdown_widget_items(self.cv_sample_mediums, current_sample_medium) self.fields['sample_medium'].widget = forms.Select(choices=cv_sample_medium_choices) cv_units_type_choices = _get_cv_dropdown_widget_items(self.cv_units_types, current_units_type) self.fields['units_type'].widget = forms.Select(choices=cv_units_type_choices) cv_status_choices = _get_cv_dropdown_widget_items(self.cv_statuses, current_status) self.fields['status'].widget = forms.Select(choices=cv_status_choices) cv_agg_statistics_choices = _get_cv_dropdown_widget_items(self.cv_aggregation_statistics, current_agg_statistics) self.fields['aggregation_statistics'].widget = forms.Select( choices=cv_agg_statistics_choices)

Example 61

View licensedef _set_element_code_selection_form_field(form, form_field_name, form_field_label, element_id, elements, element_code_att_name, element_name_att_name): element_display_str = "{code_att_name}:{name_att_name}" if len(elements) > 0: if len(form.initial) > 0: element_code_choices = [(getattr(element, element_code_att_name), element_display_str.format( code_att_name=str(getattr(element, element_code_att_name)), name_att_name=getattr(element, element_name_att_name)) ) for element in elements if element.id != element_id] element_code_choices = tuple([(form.initial[element_code_att_name], element_display_str.format( code_att_name=str(form.initial[element_code_att_name]), name_att_name=form.initial[element_name_att_name]))] + element_code_choices + [("----", "----")]) else: element_code_choices = [(getattr(element, element_code_att_name), element_display_str.format( code_att_name=str(getattr(element, element_code_att_name)), name_att_name=getattr(element, element_name_att_name))) for element in elements] element_code_choices = tuple([("----", "----")] + element_code_choices) form.fields[form_field_name].widget = forms.Select( choices=element_code_choices) form.fields[form_field_name].label = form_field_label

Example 62

View license def _get_field(self, question): """ Create a form field based on a question. """ # multiple choice field (select) if question.type == 'M': choices = [('','')] + [(c, c) for c in question.get_possible_answers()] return forms.ChoiceField( label=question.text, required=question.required, widget=forms.Select(attrs={'class':'select_choice_field'}), choices=choices) # multiple choice field (radio) if question.type == 'R': choices = [(c, c) for c in question.get_possible_answers()] return forms.ChoiceField( label=question.text, required=question.required, widget=forms.RadioSelect(attrs={'class':'radio_choice_field'}), choices=choices) # multiple choice field (checkbox) if question.type == 'C': choices = [(c, c) for c in question.get_possible_answers()] return forms.MultipleChoiceField( label=question.text, required=question.required, widget=forms.CheckboxSelectMultiple(attrs={'class':'checkbox_choice_field'}), choices=choices) # short text field elif question.type == 'S': return forms.CharField( label=question.text, required=question.required, widget=forms.TextInput(attrs={'class':'short_text_field'})) # long text field elif question.type == 'L': return forms.CharField( label=question.text, required=question.required, widget=forms.Textarea(attrs={'class':'long_text_field'}))

Example 63

View license def testForeignKey(self): self.assertFormfield(models.Event, 'band', forms.Select)

Example 64

View license def make_entry_field(self, fieldsubmission=None): current = Semester.current() # always limit to 10 years on either side of today: that seems like a reasonable window queryset = Semester.objects \ .filter(name__gte=current.offset_name(-30), name__lte=current.offset_name(30)) \ .order_by('name') allowed = self.config.get('allowed_semesters', 'AL') if allowed == 'AL': initial = current.name elif allowed == 'LT': queryset = queryset.filter(name__lt=current.name).order_by('-name') initial = current.offset_name(-1) elif allowed == 'LE': queryset = queryset.filter(name__lte=current.name).order_by('-name') initial = current.name elif allowed == 'GT': queryset = queryset.filter(name__gt=current.name) initial = current.offset_name(1) elif allowed == 'GE': queryset = queryset.filter(name__gte=current.name) initial = current.name the_choices = [(s.name, s.label()) for s in queryset] widget = forms.Select if self.config.get('format', 'D') == 'R': widget = forms.RadioSelect required = self.config['required'] if not required: initial = None c = forms.ChoiceField(required=required, label=self.config['label'], help_text=self.config['help_text'], choices=the_choices, widget=widget, initial=initial) if fieldsubmission: c.initial = fieldsubmission.data['info'] if not self.config['required']: c.choices.insert(0, ('', u'\u2014')) return c

Example 65

View license def testFieldWithChoices(self): self.assertFormfield(models.Member, 'gender', forms.Select)

Example 66

View license def __init__(self, attrs=None): widgets = (forms.Select(attrs=attrs, choices=([(hour,hour) for hour in range(0,24)])), forms.Select(attrs=attrs, choices=([(minute, str(minute).zfill(2)) for \ minute in [0,15,30,45]]))) super(SplitTimeWidget, self).__init__(widgets, attrs)

Example 67

View license def __init__(self, data=None, initial=None): super(TrelloForm, self).__init__(data=data, initial=initial) self.fields['board_list'].widget = forms.Select(choices=initial.get('trello_list', ()))

Example 68

View license def get_fields(self, request, category=None): return [("sort", forms.CharField(required=False, widget=forms.Select(), label=_('Sort')))]

Example 69

View license def __init__(self, *args, **kwargs): errors = self.default_error_messages.copy() if 'error_messages' in kwargs: errors.update(kwargs['error_messages']) fields = ( forms.ChoiceField( choices=[('', _('Month'))] + self.EXP_MONTH, error_messages={'invalid': errors['invalid_month']}, widget=forms.Select( attrs={'autocomplete': 'cc-exp-month', 'required': 'required'})), forms.ChoiceField( choices=[('', _('Year'))] + self.EXP_YEAR, error_messages={'invalid': errors['invalid_year']}, widget=forms.Select( attrs={'autocomplete': 'cc-exp-year', 'required': 'required'})), ) super(CreditCardExpiryField, self).__init__(fields, *args, **kwargs) self.widget = CreditCardExpiryWidget(widgets=[fields[0].widget, fields[1].widget])

Example 70

View license def __init__(self, *args, **kwargs): errors = self.default_error_messages.copy() if 'error_messages' in kwargs: errors.update(kwargs['error_messages']) fields = ( forms.ChoiceField( choices=[('', _('Month'))] + self.EXP_MONTH, error_messages={'invalid': errors['invalid_month']}, widget=forms.Select( attrs={'autocomplete': 'cc-exp-month', 'required': 'required'})), forms.ChoiceField( choices=[('', _('Year'))] + self.EXP_YEAR, error_messages={'invalid': errors['invalid_year']}, widget=forms.Select( attrs={'autocomplete': 'cc-exp-year', 'required': 'required'})), ) super(CreditCardExpiryField, self).__init__(fields, *args, **kwargs) self.widget = CreditCardExpiryWidget(widgets=[fields[0].widget, fields[1].widget])

Example 71

View license def __init__(self, enable_cases=True, enable_forms=True): self.all_sources = {} self.enable_cases = enable_cases self.enable_forms = enable_forms source_choices = [] if enable_cases: source_choices.append(("case", _("Case"))) if enable_forms: source_choices.append(("form", _("Form"))) self.application_field = forms.ChoiceField(label=_('Application'), widget=forms.Select()) if enable_cases and enable_forms: self.source_type_field = forms.ChoiceField(label=_('Type of Data'), choices=source_choices, widget=forms.Select(choices=source_choices)) else: self.source_type_field = forms.ChoiceField(choices=source_choices, widget=forms.HiddenInput(), initial=source_choices[0][0]) self.source_field = forms.ChoiceField(label=_('Data Source'), widget=forms.Select())

Example 74

View license def get_fields(self, request, category=None): return [("sort", forms.CharField(required=False, widget=forms.Select(), label=_('Sort')))]

Example 75

View license def __init__(self, *args, **kwargs): super(AdvancedSettingsForm, self).__init__(*args, **kwargs) self.fields['language'].widget = HiddenInput() self.fields['site'].widget = HiddenInput() site_id = self.fields['site'].initial languages = get_language_tuple(site_id) self.fields['language'].choices = languages if not self.fields['language'].initial: self.fields['language'].initial = get_language() if 'navigation_extenders' in self.fields: navigation_extenders = self.get_navigation_extenders() self.fields['navigation_extenders'].widget = forms.Select( {}, [('', "---------")] + navigation_extenders) if 'application_urls' in self.fields: # Prepare a dict mapping the apps by class name ('PollApp') to # their app_name attribute ('polls'), if any. app_namespaces = {} app_configs = {} for hook in apphook_pool.get_apphooks(): app = apphook_pool.get_apphook(hook[0]) if app.app_name: app_namespaces[hook[0]] = app.app_name if app.app_config: app_configs[hook[0]] = app self.fields['application_urls'].widget = AppHookSelect( attrs={'id': 'application_urls'}, app_namespaces=app_namespaces ) self.fields['application_urls'].choices = [('', "---------")] + apphook_pool.get_apphooks() page_data = self.data if self.data else self.initial if app_configs: self.fields['application_configs'].widget = ApplicationConfigSelect( attrs={'id': 'application_configs'}, app_configs=app_configs) if page_data.get('application_urls', False) and page_data['application_urls'] in app_configs: self.fields['application_configs'].choices = [(config.pk, force_text(config)) for config in app_configs[page_data['application_urls']].get_configs()] apphook = page_data.get('application_urls', False) try: config = apphook_pool.get_apphook(apphook).get_configs().get(namespace=self.initial['application_namespace']) self.fields['application_configs'].initial = config.pk except ObjectDoesNotExist: # Provided apphook configuration doesn't exist (anymore), # just skip it # The user will choose another value anyway pass else: # If app_config apphook is not selected, drop any value # for application_configs to avoid the field data from # being validated by the field itself try: del self.data['application_configs'] except KeyError: pass if 'redirect' in self.fields: self.fields['redirect'].widget.language = self.fields['language'].initial

Example 77

View license def __init__(self, *args, **kwargs): company = kwargs.pop('company') super(DeletedPeopleForm, self).__init__(*args, **kwargs) self.fields['person'] = forms.ModelChoiceField(queryset=Person.objects.filter(company=company, is_active=False), widget=forms.Select(attrs={'class': 'span3'}))

Example 78

View license def __init__(self, article, request, *args, **kwargs): self.article = article self.user = request.user self.request = request kwargs['instance'] = article kwargs['initial'] = {'locked': article.current_revision.locked} super(PermissionsForm, self).__init__(*args, **kwargs) self.can_change_groups = False self.can_assign = False if permissions.can_assign(article, request.user): self.can_assign = True self.can_change_groups = True self.fields['group'].queryset = models.Group.objects.all() elif permissions.can_assign_owner(article, request.user): self.fields['group'].queryset = models.Group.objects.filter(user=request.user) self.can_change_groups = True else: # Quick-fix... # Set the group dropdown to readonly and with the current # group as only selectable option self.fields['group'] = forms.ModelChoiceField( queryset = models.Group.objects.filter(id=self.instance.group.id) if self.instance.group else models.Group.objects.none(), empty_label = _('(none)'), required = False, widget = SelectWidgetBootstrap(disabled=True) if settings.USE_BOOTSTRAP_SELECT_WIDGET else forms.Select(attrs={'disabled': True}) ) self.fields['group_read'].widget = forms.HiddenInput() self.fields['group_write'].widget = forms.HiddenInput() if not self.can_assign: self.fields['owner_username'].widget = forms.TextInput(attrs={'readonly': 'true'}) self.fields['recursive'].widget = forms.HiddenInput() self.fields['recursive_group'].widget = forms.HiddenInput() self.fields['recursive_owner'].widget = forms.HiddenInput() self.fields['locked'].widget = forms.HiddenInput() self.fields['owner_username'].initial = getattr(article.owner, User.USERNAME_FIELD) if article.owner else ""

Example 79

View license def get_fields(self, request, category=None): return [("sort", forms.CharField(required=False, widget=forms.Select(), label=_('Sort')))]

Example 80

View license def __init__(self, attrs={}, choices=(), disabled=False): attrs['class'] = 'btn-group pull-left btn-group-form' self.disabled = disabled self.noscript_widget = forms.Select(attrs={}, choices=choices) super(SelectWidgetBootstrap, self).__init__(attrs, choices)

Example 81

View license def get_form(self, form_class): stage_configurations = self.stage.get_queryset_configurations() form = form_class(**self.get_form_kwargs()) used_arg_names = [] # We want to inject fields into the form for the configurations they've marked as prompt for config in stage_configurations: if config.task_argument and config.task_name != self.task_name: continue if not config.prompt_me_for_input: if config.task_argument: used_arg_names.append(config.key) continue str_config_key = 'configuration_value_for_{}'.format(config.key) if config.data_type == config.BOOLEAN_TYPE: field = BooleanField(widget=Select(choices=((False, 'False'), (True, 'True')))) field.coerce=lambda x: x == 'True', elif config.data_type == config.NUMBER_TYPE: field = FloatField() else: field = CharField() if config.sensitive_value: field.widget = PasswordInput() if config.task_argument: used_arg_names.append(config.key) field.label = 'Argument value for ' + config.key field.initial = config.value form.fields[str_config_key] = field form.helper.layout.fields.insert(len(form.helper.layout.fields)-1, str_config_key) task_details = backend.get_task_details(self.stage.project, self.task_name) for arg in task_details[2]: if isinstance(arg, tuple): name, default = arg else: name, default = arg, None if name in used_arg_names: continue str_config_key = 'configuration_value_for_{}'.format(name) field = CharField(label='Argument value for ' + name, initial=default) form.fields[str_config_key] = field form.helper.layout.fields.insert(len(form.helper.layout.fields)-1, str_config_key) return form

Example 82

View license def __init__(self, article, request, *args, **kwargs): self.article = article self.user = request.user self.request = request kwargs['instance'] = article kwargs['initial'] = {'locked': article.current_revision.locked} super(PermissionsForm, self).__init__(*args, **kwargs) self.can_change_groups = False self.can_assign = False if permissions.can_assign(article, request.user): self.can_assign = True self.can_change_groups = True self.fields['group'].queryset = models.Group.objects.all() elif permissions.can_assign_owner(article, request.user): self.fields['group'].queryset = models.Group.objects.filter(user=request.user) self.can_change_groups = True else: # Quick-fix... # Set the group dropdown to readonly and with the current # group as only selectable option self.fields['group'] = forms.ModelChoiceField( queryset = models.Group.objects.filter(id=self.instance.group.id) if self.instance.group else models.Group.objects.none(), empty_label = _('(none)'), required = False, widget = SelectWidgetBootstrap(disabled=True) if settings.USE_BOOTSTRAP_SELECT_WIDGET else forms.Select(attrs={'disabled': True}) ) self.fields['group_read'].widget = forms.HiddenInput() self.fields['group_write'].widget = forms.HiddenInput() if not self.can_assign: self.fields['owner_username'].widget = forms.TextInput(attrs={'readonly': 'true'}) self.fields['recursive'].widget = forms.HiddenInput() self.fields['recursive_group'].widget = forms.HiddenInput() self.fields['recursive_owner'].widget = forms.HiddenInput() self.fields['locked'].widget = forms.HiddenInput() self.fields['owner_username'].initial = getattr(article.owner, User.USERNAME_FIELD) if article.owner else ""

Example 83

View license def get_form_field(self, form_class=forms.CharField, **kwargs): """Return a Django form field appropriate for this property. Args: form_class: a forms.Field subclass, default forms.CharField Additional keyword arguments are passed to the form_class constructor, with certain defaults: required: self.required label: prettified self.verbose_name, if not None widget: a forms.Select instance if self.choices is non-empty initial: self.default, if not None Returns: A fully configured instance of form_class, or None if no form field should be generated for this property. """ defaults = {'required': self.required} if self.verbose_name: defaults['label'] = self.verbose_name.capitalize().replace('_', ' ') if self.choices: choices = [] if not self.required or (self.default is None and 'initial' not in kwargs): choices.append(('', '---------')) for choice in self.choices: choices.append((str(choice), unicode(choice))) defaults['widget'] = forms.Select(choices=choices) if self.default is not None: defaults['initial'] = self.default defaults.update(kwargs) return form_class(**defaults)

Example 84

View license def __init__(self, *args, **kwargs): from .election_specific import shorten_post_label super(UpdatePersonForm, self).__init__(*args, **kwargs) self.elections_with_fields = Election.objects.current().by_date() # The fields on this form depends on how many elections are # going on at the same time. (FIXME: this might be better done # with formsets?) for election_data in self.elections_with_fields: election = election_data.slug self.fields['standing_' + election] = \ forms.ChoiceField( label=_('Standing in %s') % election_data.name, choices=self.STANDING_CHOICES, widget=forms.Select(attrs={'class': 'standing-select'}), ) self.fields['constituency_' + election] = \ forms.ChoiceField( label=_('Constituency in %s') % election_data.name, required=False, choices=[('', '')] + sorted( [ (post.extra.slug, shorten_post_label(post.label)) for post in Post.objects.select_related('extra').filter(extra__elections__slug=election) ], key=lambda t: t[1] ), widget=forms.Select(attrs={'class': 'post-select'}), ) for party_set in PartySet.objects.all(): self.fields['party_' + party_set.slug + '_' + election] = \ forms.ChoiceField( label=_("Party in {election} ({party_set_name})").format( election=election_data.name, party_set_name=party_set.name, ), choices=party_set.party_choices(), required=False, widget=forms.Select( attrs={ 'class': 'party-select party-select-' + election } ), ) if election_data.party_lists_in_use: # Then add a field to enter the position on the party list # as an integer: field_name = 'party_list_position_' + party_set.slug + \ '_' + election self.fields[field_name] = forms.IntegerField( label=_("Position in party list ('1' for first, '2' for second, etc.)"), min_value=1, required=False, widget=forms.NumberInput( attrs={ 'class': 'party-position party-position-' + election } ) )

Example 85

View license def __init__(self, *args, **kwargs): from .election_specific import shorten_post_label super(UpdatePersonForm, self).__init__(*args, **kwargs) self.elections_with_fields = Election.objects.current().by_date() # The fields on this form depends on how many elections are # going on at the same time. (FIXME: this might be better done # with formsets?) for election_data in self.elections_with_fields: election = election_data.slug self.fields['standing_' + election] = \ forms.ChoiceField( label=_('Standing in %s') % election_data.name, choices=self.STANDING_CHOICES, widget=forms.Select(attrs={'class': 'standing-select'}), ) self.fields['constituency_' + election] = \ forms.ChoiceField( label=_('Constituency in %s') % election_data.name, required=False, choices=[('', '')] + sorted( [ (post.extra.slug, shorten_post_label(post.label)) for post in Post.objects.select_related('extra').filter(extra__elections__slug=election) ], key=lambda t: t[1] ), widget=forms.Select(attrs={'class': 'post-select'}), ) for party_set in PartySet.objects.all(): self.fields['party_' + party_set.slug + '_' + election] = \ forms.ChoiceField( label=_("Party in {election} ({party_set_name})").format( election=election_data.name, party_set_name=party_set.name, ), choices=party_set.party_choices(), required=False, widget=forms.Select( attrs={ 'class': 'party-select party-select-' + election } ), ) if election_data.party_lists_in_use: # Then add a field to enter the position on the party list # as an integer: field_name = 'party_list_position_' + party_set.slug + \ '_' + election self.fields[field_name] = forms.IntegerField( label=_("Position in party list ('1' for first, '2' for second, etc.)"), min_value=1, required=False, widget=forms.NumberInput( attrs={ 'class': 'party-position party-position-' + election } ) )

Example 86

View license def __init__(self, attrs={}, choices=(), disabled=False): attrs['class'] = 'btn-group pull-left btn-group-form' self.disabled = disabled self.noscript_widget = forms.Select(attrs={}, choices=choices) super(SelectWidgetBootstrap, self).__init__(attrs, choices)

Example 87

View license def test_mutuallyexclusiveradiowidget(self): w = MutuallyExclusiveRadioWidget(widgets=[ forms.Select(choices=[(1, 1), (2, 2)]), forms.TextInput(attrs={'placeholder': 'Enter a number'}), ]) self.assertHTMLEqual( w.render('test', None), '<span id="test_container" class="mutually-exclusive-widget" ' 'style="display:inline-block">' '<span><input checked="" name="test_radio" type="radio" />' '<select name="test_0"><option value="1">1</option>' '<option value="2">2</option></select></span><br>' '<span><input name="test_radio" type="radio" />' '<input name="test_1" placeholder="Enter a number" type="text" />' '</span></span>') self.assertHTMLEqual( w.render('test', ''), '<span id="test_container" class="mutually-exclusive-widget" ' 'style="display:inline-block">' '<span><input checked="" name="test_radio" type="radio" />' '<select name="test_0"><option value="1">1</option>' '<option value="2">2</option></select></span><br>' '<span><input name="test_radio" type="radio" />' '<input name="test_1" placeholder="Enter a number" type="text" />' '</span></span>') self.assertHTMLEqual( w.render('test', '1'), '<span id="test_container" class="mutually-exclusive-widget" ' 'style="display:inline-block">' '<span><input checked="" name="test_radio" type="radio" />' '<select name="test_0"><option value="1">1</option>' '<option value="2">2</option></select></span><br>' '<span><input name="test_radio" type="radio" />' '<input name="test_1" placeholder="Enter a number" type="text" />' '</span></span>') self.assertHTMLEqual( w.render('test', ['1', None]), '<span id="test_container" class="mutually-exclusive-widget" ' 'style="display:inline-block">' '<span><input checked="" name="test_radio" type="radio" />' '<select name="test_0"><option value="1" selected="selected">1' '</option><option value="2">2</option></select></span><br>' '<span><input name="test_radio" type="radio" />' '<input name="test_1" placeholder="Enter a number" type="text" />' '</span></span>') self.assertHTMLEqual( w.render('test', [None, '1']), '<span id="test_container" class="mutually-exclusive-widget" ' 'style="display:inline-block">' '<span><input name="test_radio" type="radio" />' '<select name="test_0"><option value="1">1</option>' '<option value="2">2</option></select></span><br><span>' '<input checked="" name="test_radio" type="radio" />' '<input name="test_1" placeholder="Enter a number" type="text" ' 'value="1" /></span></span>')

Example 88

View license def get_fields(self, request, category=None): return [("limit", forms.IntegerField(required=False, widget=forms.Select(), label=_("Products per page")))]

Example 89

View license def test_field_with_choices(self): widget = VariegatedFieldsWidget.add_root(widgy_site) form_class = widget.get_form_class(request=None)() self.assertIsInstance(form_class.fields['color'].widget, forms.Select)

Example 91

View license def get_form_field(self, form_class=forms.CharField, **kwargs): """Return a Django form field appropriate for this property. Args: form_class: a forms.Field subclass, default forms.CharField Additional keyword arguments are passed to the form_class constructor, with certain defaults: required: self.required label: prettified self.verbose_name, if not None widget: a forms.Select instance if self.choices is non-empty initial: self.default, if not None Returns: A fully configured instance of form_class, or None if no form field should be generated for this property. """ defaults = {'required': self.required} if self.verbose_name: defaults['label'] = self.verbose_name.capitalize().replace('_', ' ') if self.choices: choices = [] if not self.required or (self.default is None and 'initial' not in kwargs): choices.append(('', '---------')) for choice in self.choices: choices.append((str(choice), unicode(choice))) defaults['widget'] = forms.Select(choices=choices) if self.default is not None: defaults['initial'] = self.default defaults.update(kwargs) return form_class(**defaults)

Example 92

View licensedef forms_form_browse_entries(request, slug, entries=None): try: form = FormsForm.objects.select_related(depth=1).get(slug=slug) except: return None # dont't verify access, caller must do it for us extra_context = {} kwargs = {} sort = '' if entries: kwargs['entries'] = entries extra_context['filters'] = {} extra_context['field_filters'] = [] form_fields = form.fields.select_related().all().order_by('label') form.fields_reference = {} hidden = request.GET.get('hidden', '') if hidden: hidden = hidden.split(',') else: hidden = [] for f in form_fields: fl = request.GET.get(f.slug, None) if fl: kwargs[f.slug] = smart_str(fl) if f.for_sort: sort = f.slug if not f.visible_in_list: hidden.append(f.slug) extra_context['params'] = urllib.urlencode(kwargs) kwargs['f'] = request.GET.get('f', '') kwargs['q'] = request.GET.get('q', '') kwargs['o'] = request.GET.get('o', sort) kwargs['ot'] = request.GET.get('ot', 'asc') kwargs['where'] = request.GET.get('where', '') extra_context['parents'] = [] if kwargs['where']: try: bte = kwargs['where'].split(':') extra_context['where_entry_id'] = entry_id = bte[1] bte = bte[0].split('.') extra_context['where_form_slug'] = form_slug = bte[0] extra_context['where_form_field'] = form_field = bte[1] while entry_id: e = FormsFormEntry.objects.select_related().get( pk=entry_id, form__slug=form_slug) c, r = forms_get_entry(e) extra_context['parents'].append({'row': r[ form_field], 'entry': e}) hidden.append(r[form_field]['slug']) if not e.form.bind_to_entry: break bte = e.form.bind_to_entry.split('.') form_slug = bte[0] form_field = bte[1] entry_id = e.entry.pk except Exception as e: extra_context['parents'] = [] extra_context['parents'].reverse() kwargs['hidden'] = ','.join(hidden) columns, entries = forms_get_entries(form, **kwargs) for f in form_fields: if '.' in f.reference and f.is_a(*fields.CHOICES): fl = request.GET.get(f.slug, None) choices = [('', '--- %s ---' % f.label)] for e in form.fields_reference[f.pk]: choices.append((e[0], e[1])) s = forms.Select(choices=choices) extra_context['filters'][f.label] = s.render(f.slug, fl, None) else: extra_context['field_filters'].append([f.label, f.slug]) if fl: kwargs[f.slug] = fl paginator = Paginator(entries, 25) page = int(request.GET.get('page', 1)) try: rows = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. rows = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. rows = paginator.page(paginator.num_pages) extra_context['q'] = kwargs['q'] extra_context['f'] = kwargs['f'] extra_context['column_filter'] = kwargs['o'] extra_context['column_order'] = kwargs['ot'] extra_context['zorna_title_page'] = _(u'Forms') extra_context['form'] = form extra_context['columns'] = columns extra_context['entries'] = entries extra_context['rows'] = rows extra_context['page'] = page extra_context['paginator'] = paginator extra_context['where'] = kwargs['where'] try: r = form.bind_to_entry.split('.') extra_context['bind_entry_slug'] = r[0] extra_context['bind_entry_field'] = r[1] except: pass extra_context['where'] = kwargs['where'] return extra_context

Example 93

View licen[email protected] def jet_select2_lookups(field): if hasattr(field, 'field') and isinstance(field.field, ModelChoiceField): qs = field.field.queryset model = qs.model if getattr(model, 'autocomplete_search_fields', None) and getattr(field.field, 'autocomplete', True): choices = [] app_label = model._meta.app_label model_name = model._meta.object_name attrs = { 'class': 'ajax', 'data-app-label': app_label, 'data-model': model_name, 'data-ajax--url': reverse('jet:model_lookup') } form = field.form initial_value = form.data.get(field.name) if form.data != {} else form.initial.get(field.name) if hasattr(field, 'field') and isinstance(field.field, ModelMultipleChoiceField): if initial_value: initial_objects = model.objects.filter(pk__in=initial_value) choices.extend( [(initial_object.pk, get_model_instance_label(initial_object)) for initial_object in initial_objects] ) if isinstance(field.field.widget, RelatedFieldWidgetWrapper): field.field.widget.widget = SelectMultiple(attrs) else: field.field.widget = SelectMultiple(attrs) field.field.choices = choices elif hasattr(field, 'field') and isinstance(field.field, ModelChoiceField): if initial_value: initial_object = model.objects.get(pk=initial_value) attrs['data-object-id'] = initial_value choices.append((initial_object.pk, get_model_instance_label(initial_object))) if isinstance(field.field.widget, RelatedFieldWidgetWrapper): field.field.widget.widget = Select(attrs) else: field.field.widget = Select(attrs) field.field.choices = choices return field

Example 94

View license def get_form_field(self, form_class=forms.CharField, **kwargs): """Return a Django form field appropriate for this property. Args: form_class: a forms.Field subclass, default forms.CharField Additional keyword arguments are passed to the form_class constructor, with certain defaults: required: self.required label: prettified self.verbose_name, if not None widget: a forms.Select instance if self.choices is non-empty initial: self.default, if not None Returns: A fully configured instance of form_class, or None if no form field should be generated for this property. """ defaults = {'required': self.required} if self.verbose_name: defaults['label'] = self.verbose_name.capitalize().replace('_', ' ') if self.choices: choices = [] if not self.required or (self.default is None and 'initial' not in kwargs): choices.append(('', '---------')) for choice in self.choices: choices.append((str(choice), unicode(choice))) defaults['widget'] = forms.Select(choices=choices) if self.default is not None: defaults['initial'] = self.default defaults.update(kwargs) return form_class(**defaults)

Example 95

View [email protected]_db @pytest.mark.parametrize("form_class,get_object,service_provider_attr", [ (PaymentMethodForm, get_default_payment_method, "payment_processor"), (ShippingMethodForm, get_default_shipping_method, "carrier") ]) def test_choice_identifier_in_method_form(rf, admin_user, form_class, get_object, service_provider_attr): object = get_object() assert object.pk service_provider = getattr(object, service_provider_attr) form = form_class(instance=object, languages=settings.LANGUAGES, request=rf.get("/")) assert "choice_identifier" in form.fields assert len(form.fields["choice_identifier"].choices) == len(service_provider.get_service_choices()) assert form.fields["choice_identifier"].widget.__class__ == forms.Select assert getattr(object, service_provider_attr) setattr(object, service_provider_attr, None) # No service provider so no choice_identifier-field form = form_class(instance=object, languages=settings.LANGUAGES, request=rf.get("/")) assert "choice_identifier" in form.fields assert len(form.fields["choice_identifier"].choices) == 0 # Choices for default provider

Example 96

View [email protected]_member_required def match_columns(request, import_log_id): """ View to match import spreadsheet columns with database fields """ import_log = get_object_or_404(ImportLog, id=import_log_id) if not request.user.is_superuser and import_log.user != request.user: raise SuspiciousOperation("Non superuser attempting to view other users import") # need to generate matches if they don't exist already existing_matches = import_log.get_matches() MatchFormSet = inlineformset_factory(ImportSetting, ColumnMatch, form=MatchForm, extra=0) import_data = import_log.get_import_file_as_list() header_row = [x.lower() for x in import_data[0]] # make all lower try: sample_row = import_data[1] except IndexError: messages.error(request, 'Error: Spreadsheet was empty.') return redirect('simple_import-start_import') errors = [] model_class = import_log.import_setting.content_type.model_class() field_names = get_all_field_names(model_class) for field_name in field_names: field_object = model_class._meta.get_field(field_name) # We can't add a new AutoField and specify it's value if import_log.import_type == "N" and isinstance(field_object, AutoField): field_names.remove(field_name) if request.method == 'POST': formset = MatchFormSet(request.POST, instance=import_log.import_setting) if formset.is_valid(): formset.save() if import_log.import_type in ["U", "O"]: update_key = request.POST.get('update_key', '') if update_key: field_name = import_log.import_setting.columnmatch_set.get(column_name=update_key).field_name if field_name: field_object = model_class._meta.get_field(field_name) direct = field_object.concrete if direct and field_object.unique: import_log.update_key = update_key import_log.save() else: errors += ['Update key must be unique. Please select a unique field.'] else: errors += ['Update key must matched with a column.'] else: errors += ['Please select an update key. This key is used to linked records for updating.'] errors += validate_match_columns( import_log, model_class, header_row) all_field_names = [] for clean_data in formset.cleaned_data: if clean_data['field_name']: if clean_data['field_name'] in all_field_names: errors += ["{0} is duplicated.".format(clean_data['field_name'])] all_field_names += [clean_data['field_name']] if not errors: return HttpResponseRedirect(reverse( match_relations, kwargs={'import_log_id': import_log.id})) else: formset = MatchFormSet(instance=import_log.import_setting, queryset=existing_matches) field_choices = (('', 'Do Not Use'),) for field_name in field_names: field_object = model_class._meta.get_field(field_name) direct = field_object.concrete m2m = field_object.many_to_many add = True if direct: field_verbose = field_object.verbose_name else: field_verbose = field_name if direct and not field_object.blank: field_verbose += " (Required)" if direct and field_object.unique: field_verbose += " (Unique)" if m2m or isinstance(field_object, ForeignKey): field_verbose += " (Related)" elif not direct: add = False if is_foreign_key_id_name(field_name, field_object): add = False if add: field_choices += ((field_name, field_verbose),) # Include defined methods # Model must have a simple_import_methods defined if hasattr(model_class, 'simple_import_methods'): for import_method in model_class.simple_import_methods: field_choices += (("simple_import_method__{0}".format(import_method), "{0} (Method)".format(import_method)),) # User model should allow set password if issubclass(model_class, User): field_choices += (("simple_import_method__{0}".format('set_password'), "Set Password (Method)"),) for i, form in enumerate(formset): form.fields['field_name'].widget = forms.Select(choices=(field_choices)) form.sample = sample_row[i] return render( request, 'simple_import/match_columns.html', {'import_log': import_log, 'formset': formset, 'errors': errors}, )

Example 97

View license def get_form_field(self, form_class=forms.CharField, **kwargs): """Return a Django form field appropriate for this property. Args: form_class: a forms.Field subclass, default forms.CharField Additional keyword arguments are passed to the form_class constructor, with certain defaults: required: self.required label: prettified self.verbose_name, if not None widget: a forms.Select instance if self.choices is non-empty initial: self.default, if not None Returns: A fully configured instance of form_class, or None if no form field should be generated for this property. """ defaults = {'required': self.required} if self.verbose_name: defaults['label'] = self.verbose_name.capitalize().replace('_', ' ') if self.choices: choices = [] if not self.required or (self.default is None and 'initial' not in kwargs): choices.append(('', '---------')) for choice in self.choices: choices.append((str(choice), unicode(choice))) defaults['widget'] = forms.Select(choices=choices) if self.default is not None: defaults['initial'] = self.default defaults.update(kwargs) return form_class(**defaults)

Example 98

View [email protected]_member_required def match_relations(request, import_log_id): import_log = get_object_or_404(ImportLog, id=import_log_id) model_class = import_log.import_setting.content_type.model_class() matches = import_log.get_matches() field_names = [] choice_set = [] for match in matches.exclude(field_name=""): field_name = match.field_name if not field_name.startswith('simple_import_method__'): field = model_class._meta.get_field(field_name) m2m = field.many_to_many if m2m or isinstance(field, ForeignKey): RelationalMatch.objects.get_or_create( import_log=import_log, field_name=field_name) field_names.append(field_name) choices = () if hasattr(field, 'related'): try: parent_model = field.related.parent_model() except AttributeError: # Django 1.8+ parent_model = field.related.model else: parent_model = field.related_model for field in get_direct_fields_from_model(parent_model): if field.unique: choices += ((field.name, str(field.verbose_name)),) choice_set += [choices] existing_matches = import_log.relationalmatch_set.filter(field_name__in=field_names) MatchRelationFormSet = inlineformset_factory( ImportLog, RelationalMatch, form=MatchRelationForm, extra=0) if request.method == 'POST': formset = MatchRelationFormSet(request.POST, instance=import_log) if formset.is_valid(): formset.save() url = reverse('simple_import-do_import', kwargs={'import_log_id': import_log.id}) if 'commit' in request.POST: url += "?commit=True" return HttpResponseRedirect(url) else: formset = MatchRelationFormSet(instance=import_log) for i, form in enumerate(formset.forms): choices = choice_set[i] form.fields['related_field_name'].widget = forms.Select(choices=choices) return render( request, 'simple_import/match_relations.html', {'formset': formset, 'existing_matches': existing_matches}, )

Example 99

View license def __init__(self, *args, **kwargs): workflow = kwargs['action'].workflow del kwargs['action'] super(DefaultLinkForm, self).__init__(*args, **kwargs) self.fields['child'].widget = forms.Select(choices=((node.id, node) for node in set(workflow.node_set.all())))

Example 100

View license def __init__(self, *args, **kwargs): widgets = [forms.Select(), LabelTextInput(label=" or User ID", attrs={'size': 8, 'maxlength': 8})] kwargs['widgets'] = widgets super(SupervisorWidget, self).__init__(*args, **kwargs)
Sours: https://programtalk.com/python-examples/django.forms.Select/?ipage=2
  1. Person waving clipart
  2. Nfl games on dish today
  3. Goulds tree service
  4. Cjaa timing belt kit
  5. Core bond vs core plus

django.forms Select Example Code

Select is a class within the django.forms module of the Django project.

Example 1 from dccnsys

dccnsys is a conference registration system built with Django. The code is open source under the MIT license.

dccnsys / wwwdccn / gears / widgets.py

# widgets.pyfromdjango.formsimportFileInput,CheckboxSelectMultiple,SelectclassCustomFileInput(FileInput):template_name='gears/widgets/file_input.html'accept=''show_file_name=TrueclassCustomCheckboxSelectMultiple(CheckboxSelectMultiple):template_name='gears/widgets/checkbox_multiple_select.html'hide_label=Falsehide_apply_btn=FalseclassMedia:js=('gears/js/checkbox_multiple_select.js',)def__init__(self,*args,**kwargs):self.hide_label=kwargs.pop('hide_label',False)self.hide_apply_btn=kwargs.pop('hide_apply_btn',False)super().__init__(*args,**kwargs)defget_context(self,name,value,attrs):context=super().get_context(name,value,attrs)context['widget'].update({'hide_label':self.hide_label,'hide_apply_btn':self.hide_apply_btn,})returncontextclassDropdownSelectSubmit(Select):template_name='gears/widgets/dropdown_select_submit.html'empty_label='Not selected'label_class=''empty_label_class='text-warning'nonempty_label_class='text-success'classMedia:js=('gears/js/dropdown_select_submit.js',)def__init__(self,*args,**kwargs):self.empty_label=kwargs.pop('empty_label','Not selected')self.label_class=kwargs.pop('label_class','')self.empty_label_class=kwargs.pop('empty_label_class','text-warning')self.nonempty_label_class=kwargs.pop('nonempty_label_class','text-success')super().__init__(*args,**kwargs)defget_context(self,name,value,attrs):context=super().get_context(name,value,attrs)widget=context['widget']widget['label_class']=self.label_classwidget['empty_label_class']=self.empty_label_classwidget['nonempty_label_class']=self.nonempty_label_classwidget['label']=self.empty_label## ... source file continues with no further Select examples...

Example 2 from django-jet

django-jet (project documentation, PyPI project page and more information) is a fancy Django Admin panel replacement.

The django-jet project is open source under the GNU Affero General Public License v3.0.

django-jet / jet / templatetags / jet_tags.py

# jet_tags.pyfrom__future__importunicode_literalsimportjsonimportosfromdjangoimporttemplatetry:fromdjango.core.urlresolversimportreverseexceptImportError:# Django 1.11fromdjango.urlsimportreversefromdjango.formsimportCheckboxInput,ModelChoiceField,Select,ModelMultipleChoiceField,SelectMultiplefromdjango.contrib.admin.widgetsimportRelatedFieldWidgetWrapperfromdjango.utils.formatsimportget_formatfromdjango.utils.safestringimportmark_safefromdjango.utils.encodingimportsmart_textfromjetimportsettings,VERSIONfromjet.modelsimportBookmarkfromjet.utilsimportget_model_instance_label,get_model_queryset,get_possible_language_codes, \ get_admin_site,get_menu_itemstry:fromurllib.parseimportparse_qslexceptImportError:fromurlparseimportparse_qslregister=template.Library()assignment_tag=register.assignment_tagifhasattr(register,'assignment_tag')[email protected]_tagdefjet_get_date_format():returnget_format('DATE_INPUT_FORMATS')[0]## ... source file abbreviated to get to Select examples ...initial_value=field.value()ifhasattr(field,'field')andisinstance(field.field,ModelMultipleChoiceField):ifinitial_value:initial_objects=model.objects.filter(pk__in=initial_value)choices.extend([(initial_object.pk,get_model_instance_label(initial_object))forinitial_objectininitial_objects])ifisinstance(field.field.widget,RelatedFieldWidgetWrapper):field.field.widget.widget=SelectMultiple(attrs)else:field.field.widget=SelectMultiple(attrs)field.field.choices=choiceselifhasattr(field,'field')andisinstance(field.field,ModelChoiceField):ifinitial_value:try:initial_object=model.objects.get(pk=initial_value)attrs['data-object-id']=initial_valuechoices.append((initial_object.pk,get_model_instance_label(initial_object)))exceptmodel.DoesNotExist:passifisinstance(field.field.widget,RelatedFieldWidgetWrapper):field.field.widget.widget=Select(attrs)else:field.field.widget=Select(attrs)[email protected]_tag(takes_context=True)defjet_get_current_theme(context):if'request'incontextand'JET_THEME'incontext['request'].COOKIES:theme=context['request'].COOKIES['JET_THEME']ifisinstance(settings.JET_THEMES,list)andlen(settings.JET_THEMES)>0:forconf_themeinsettings.JET_THEMES:ifisinstance(conf_theme,dict)andconf_theme.get('theme')==theme:[email protected]_tagdefjet_get_themes():[email protected]_tagdefjet_get_current_version():returnVERSION## ... source file continues with no further Select examples...
Sours: https://www.fullstackpython.com/django-forms-select-examples.html
Python Django Simple Dropdown List Binding Populate Data

Documentation

Inline formsets¶

class

Inline formsets is a small abstraction layer on top of model formsets. These simplify the case of working with related objects via a foreign key. Suppose you have these two models:

fromdjango.dbimportmodelsclassAuthor(models.Model):name=models.CharField(max_length=100)classBook(models.Model):author=models.ForeignKey(Author,on_delete=models.CASCADE)title=models.CharField(max_length=100)

If you want to create a formset that allows you to edit books belonging to a particular author, you could do this:

>>> fromdjango.formsimportinlineformset_factory>>> BookFormSet=inlineformset_factory(Author,Book,fields=('title',))>>> author=Author.objects.get(name='Mike Royko')>>> formset=BookFormSet(instance=author)

’s prefix is ( ). If ’s to has a , that’s used instead.

Overriding methods on an ¶

When overriding methods on , you should subclass rather than .

For example, if you want to override :

fromdjango.formsimportBaseInlineFormSetclassCustomInlineFormSet(BaseInlineFormSet):defclean(self):super().clean()# example custom validation across forms in the formsetforforminself.forms:# your custom formset validation...

See also Overriding clean() on a ModelFormSet.

Then when you create your inline formset, pass in the optional argument :

>>> fromdjango.formsimportinlineformset_factory>>> BookFormSet=inlineformset_factory(Author,Book,fields=('title',),... formset=CustomInlineFormSet)>>> author=Author.objects.get(name='Mike Royko')>>> formset=BookFormSet(instance=author)

More than one foreign key to the same model¶

If your model contains more than one foreign key to the same model, you’ll need to resolve the ambiguity manually using . For example, consider the following model:

classFriendship(models.Model):from_friend=models.ForeignKey(Friend,on_delete=models.CASCADE,related_name='from_friends',)to_friend=models.ForeignKey(Friend,on_delete=models.CASCADE,related_name='friends',)length_in_months=models.IntegerField()

To resolve this, you can use to :

>>> FriendshipFormSet=inlineformset_factory(Friend,Friendship,fk_name='from_friend',... fields=('to_friend','length_in_months'))

Using an inline formset in a view¶

You may want to provide a view that allows a user to edit the related objects of a model. Here’s how you can do that:

defmanage_books(request,author_id):author=Author.objects.get(pk=author_id)BookInlineFormSet=inlineformset_factory(Author,Book,fields=('title',))ifrequest.method=="POST":formset=BookInlineFormSet(request.POST,request.FILES,instance=author)ifformset.is_valid():formset.save()# Do something. Should generally end with a redirect. For example:returnHttpResponseRedirect(author.get_absolute_url())else:formset=BookInlineFormSet(instance=author)returnrender(request,'manage_books.html',{'formset':formset})

Notice how we pass in both the and cases.

Sours: https://docs.djangoproject.com/en/3.2/topics/forms/modelforms/

Select django forms

django.forms.widgets.Select

Here are the examples of the python api django.forms.widgets.Select taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

Example 1

View license def get_form(self, request, obj=None, **kwargs): glossary_fields = list(kwargs.pop('glossary_fields', self.glossary_fields)) glossary_fields.append(GlossaryField( widgets.Select(choices=self.get_template_choices()), label=_("Render template"), name='render_template', help_text=_("Use alternative template for rendering this plugin.") )) kwargs.update(glossary_fields=glossary_fields) return super(RenderTemplateMixin, self).get_form(request, obj, **kwargs)

Example 2

View license def __init__(self, *args, **kwargs): super(ProductStockForm, self).__init__(*args, **kwargs) self.fields["ordered_at"].widget.attrs = {'class': 'date-picker'} if kwargs.get("instance").is_variant(): self.fields["active_packing_unit"].widget = Select(choices=CHOICES) else: self.fields["active_packing_unit"].widget = LFSCheckboxInput(check_test=lambda v: v != 0)

Example 3

View license def __init__(self, *args, **kwargs): mts = kwargs.pop('mts') super(ProfileSearchForm, self).__init__(*args, **kwargs) self.fields['first_name'].widget.attrs.update({'placeholder': _('Exact Match Search')}) self.fields['last_name'].widget.attrs.update({'placeholder': _('Exact Match Search')}) self.fields['email'].widget.attrs.update({'placeholder': _('Exact Match Search')}) if not mts: del self.fields['membership_type'] del self.fields['member_only'] else: choices = [(0, _('SELECT ONE'))] choices += [(mt.id, mt.name) for mt in mts] self.fields['membership_type'].widget = forms.widgets.Select( choices=choices)

Example 4

View license def create_select(self, name, field, value, val, choices, none_value): if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name if not self.is_required: choices.insert(0, 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

Example 5

View license 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

Example 6

View license 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

Example 7

View license def add_fields(self, form, index): super(BaseTranslationFormSet, self).add_fields(form, index) # Add the language code automagically if not 'language_code' in form.fields: form.fields['language_code'] = CharField( required=True, initial=form.instance.language_code, widget=Select(choices=(('', '--'),)+settings.LANGUAGES) ) # Add language_code to self._meta.fields so it is included in validation stage try: form._meta.fields.append('language_code') except AttributeError: #pragma: no cover form._meta.fields += ('language_code',) # Remove the master foreignkey, we have this from self.instance already if 'master' in form.fields: del form.fields['master']

Example 8

View license 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

Example 9

View license def __init__(self, *args, **kwargs): super(StaticPageEditForm, self).__init__(*args, **kwargs) self.fields['url'].label = 'URL' self.fields['template_name'].label = 'Template' choices = ( ('', 'Default'), ('staticpages/nosidebar.html', 'Default (but no sidebar)'), ('staticpages/blank.html', 'Blank (no template wrapping)'), ) self.fields['template_name'].widget = forms.widgets.Select( choices=choices )

Example 10

View license def formfield(self, **kwargs): """ Returns an augmented form field. """ defaults = {'widget': widgets.Select(attrs={'class': 'registry_form_selector'})} defaults.update(kwargs) return super(ModelRegistryChoiceField, self).formfield(**defaults)

Example 11

View license def get_formset(self, request, obj=None, **kwargs): """ Convert the field `payment_method` into a select box with all possible payment methods. """ choices = [pm.get_choice() for pm in cart_modifiers_pool.get_payment_modifiers()] kwargs.update(widgets={'payment_method': widgets.Select(choices=choices)}) formset = super(OrderPaymentInline, self).get_formset(request, obj, **kwargs) return formset

Example 12

View license 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

Example 13

View license def add_fields(self, form, index): super(BaseTranslationFormSet, self).add_fields(form, index) # Add the language code automagically if not 'language_code' in form.fields: form.fields['language_code'] = CharField( required=True, initial=form.instance.language_code, widget=Select(choices=(('', '--'),)+settings.LANGUAGES) ) # Add language_code to self._meta.fields so it is included in validation stage try: form._meta.fields.append('language_code') except AttributeError: #pragma: no cover form._meta.fields += ('language_code',) # Remove the master foreignkey, we have this from self.instance already if 'master' in form.fields: del form.fields['master']

Example 14

View license def get_form(self, request, obj=None, **kwargs): """ Build the form used for changing the model. """ kwargs.update(widgets={ 'plugin_type': widgets.Select(choices=self.plugins_for_site), 'css_classes': JSONMultiWidget(self.classname_fields), 'inline_styles': JSONMultiWidget(self.style_fields) }) form = super(PluginExtraFieldsAdmin, self).get_form(request, obj, **kwargs) rectify_partial_form_field(form.base_fields['css_classes'], self.classname_fields) form.classname_fields = self.classname_fields rectify_partial_form_field(form.base_fields['inline_styles'], self.style_fields) form.style_fields = self.style_fields return form

Example 15

View license def get_form(self, request, obj=None, **kwargs): glossary_fields = list(kwargs.pop('glossary_fields', self.glossary_fields)) glossary_fields.append(GlossaryField( widgets.Select(choices=self.get_template_choices()), label=_("Render template"), name='render_template', help_text=_("Use alternative template for rendering this plugin.") )) kwargs.update(glossary_fields=glossary_fields) return super(RenderTemplateMixin, self).get_form(request, obj, **kwargs)

Example 16

View license 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

Example 17

View license 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

Example 18

View license 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.is_required: 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

Example 19

View license 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

Example 20

View license def __init__(self, *args, **kwargs): super(CategoryVariantForm, self).__init__(*args, **kwargs) product = kwargs.get("instance") choices = [] for cv in CATEGORY_VARIANT_CHOICES: choices.append(cv) for variant in Product.objects.filter(parent=product): choices.append([variant.id, "%s (%s)" % (variant.get_name(), variant.variant_position)]) self.fields["category_variant"].widget = Select(choices=choices)

Example 21

View license def __init__(self, protocol, **kwargs): kwargs['queryset'] = core_models.Node.objects.regpoint('config').registry_fields( name='core.general__name', wifi_interface='core.interfaces', wifi_mode='core.interfaces__mode', ).filter( # Only show nodes which have access point interfaces configured. wifi_mode='ap', # Only show access point interfaces that are of the same mode as the station. wifi_interface__device__protocol=protocol, ).order_by( # TODO: Nodes should be sorted by distance from current node. 'name' ) kwargs['widget'] = widgets.Select(attrs={'class': 'registry_form_selector'}) super(AccessPointSelectionField, self).__init__(**kwargs)

Example 22

View license 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

Example 23

View license def __init__(self, *args, **kwargs): super(StaticPageEditForm, self).__init__(*args, **kwargs) self.fields['url'].label = 'URL' self.fields['template_name'].label = 'Template' choices = ( ('', 'Default'), ('staticpages/nosidebar.html', 'Default (but no sidebar)'), ('staticpages/blank.html', 'Blank (no template wrapping)'), ) self.fields['template_name'].widget = forms.widgets.Select( choices=choices )

Example 24

View license def __init__(self, attrs=None, **kwargs): _widgets = ( widgets.Select(attrs=attrs, **kwargs), widgets.TextInput(attrs=attrs) ) super(CustomChoiceWidget, self).__init__(_widgets, attrs)

Example 25

View license def __init__(self, rp_choices=None, *args, **kwargs): """ Class constructor. """ kwargs['widget'] = widgets.Select(attrs={'class': 'registry_form_selector'}) super(RegistryChoiceFormField, self).__init__(*args, **kwargs) # Override choices so we get a lazy list instead of being evaluated right here. self._rp_choices = None if rp_choices is not None: self._rp_choices = self._choices = self.widget.choices = rp_choices

Example 26

View license 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

Example 27

View license 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

Example 28

View license def __init__(self, *args, **kwargs): super(CorpMembershipAppFieldAdminForm, self).__init__(*args, **kwargs) if self.instance: if not self.instance.field_name: self.fields['field_type'].choices = CorpMembershipAppField.FIELD_TYPE_CHOICES2 else: self.fields['field_type'].choices = CorpMembershipAppField.FIELD_TYPE_CHOICES1 if self.instance.field_name in ['tax_exempt']: # handle boolean fields self.fields['field_type'].choices = (("BooleanField", _("Checkbox")), ("ChoiceField", _("Select One from a list (Drop Down)")), ("ChoiceField/django.forms.RadioSelect", _("Select One from a list (Radio Buttons)")),) self.fields['choices'].widget = forms.widgets.Select( choices=(('yesno', _('Yes/No')),))

Example 29

View license def __init__(self, widgets=None, attrs=None): widgets = [ ClearableFileInput(attrs=None), Select( attrs=attrs, choices=CENTERPOINT_CHOICES ) ] super(VersatileImagePPOISelectWidget, self).__init__(widgets, attrs)

Example 30

View license def get_form(self, request, obj=None, **kwargs): kwargs.update(widgets={ 'transition_target': widgets.Select(choices=self.get_transition_choices()), 'mail_to': widgets.Select(choices=self.get_mailto_choices()), }) return super(NotificationAdmin, self).get_form(request, obj, **kwargs)

Example 31

View license def get_form(self, request, obj=None, **kwargs): """ Build the form used for changing the model. """ kwargs.update(widgets={ 'plugin_type': widgets.Select(choices=self.plugins_for_site), 'css_classes': JSONMultiWidget(self.classname_fields), 'inline_styles': JSONMultiWidget(self.style_fields) }) form = super(PluginExtraFieldsAdmin, self).get_form(request, obj, **kwargs) rectify_partial_form_field(form.base_fields['css_classes'], self.classname_fields) form.classname_fields = self.classname_fields rectify_partial_form_field(form.base_fields['inline_styles'], self.style_fields) form.style_fields = self.style_fields return form

Example 32

View license 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

Example 33

View license def get_formset(self, request, obj=None, **kwargs): """ Convert the field `shipping_method` into a select box with all possible shipping methods. """ choices = [sm.get_choice() for sm in cart_modifiers_pool.get_shipping_modifiers()] kwargs.update(widgets={'shipping_method': widgets.Select(choices=choices)}) formset = super(DeliveryInline, self).get_formset(request, obj, **kwargs) return formset

Example 34

View license def __init__(self, choices_model, *args, **kwargs): """ Class constructor. :param choices_model: Choices model class """ self.choices_rid = choices_model._registry.registry_id self.filter_model = choices_model self.partially_validated_tree = None self.limit_choices_to = kwargs.pop('limit_choices_to', None) or (lambda model: True) kwargs['widget'] = widgets.Select(attrs={'class': 'registry_form_selector'}) kwargs['empty_value'] = None super(ReferenceChoiceFormField, self).__init__(*args, **kwargs)

Example 35

View license 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

Example 36

View license def __init__(self, attrs=None, choices=None): """ pass all these parameters to their respective widget constructors...""" _widgets = (widgets.Select(attrs=attrs, choices=choices), widgets.TextInput(attrs=attrs)) super(IRCWidget, self).__init__(_widgets, attrs)

Example 37

View license def set_form_field(self, widget, model_field, field_key, default_value): """ Parmams: widget -- the widget to use for displyaing the model_field model_field -- the field on the model to create a form field with field_key -- the name for the field on the form default_value -- the value to give for the field Default: None """ # Empty lists cause issues on form validation if default_value == []: default_value = None if widget and isinstance(widget, forms.widgets.Select): self.form.fields[field_key] = forms.ChoiceField(label=model_field.name, required=model_field.required, widget=widget) else: field_class = get_form_field_class(model_field) self.form.fields[field_key] = field_class(label=model_field.name, required=model_field.required, widget=widget) if default_value is not None: if isinstance(default_value, Document): # Probably a reference field, therefore, add id self.form.fields[field_key].initial = getattr(default_value, 'id', None) else: self.form.fields[field_key].initial = default_value else: self.form.fields[field_key].initial = getattr(model_field, 'default', None) if isinstance(model_field, ReferenceField): self.form.fields[field_key].choices = [(unicode(x.id), get_document_unicode(x)) for x in model_field.document_type.objects.all()] # Adding in blank choice so a reference field can be deleted by selecting blank self.form.fields[field_key].choices.insert(0, ("", "")) elif model_field.choices: self.form.fields[field_key].choices = model_field.choices for key, form_attr in CHECK_ATTRS.items(): if hasattr(model_field, key): value = getattr(model_field, key) setattr(self.form.fields[field_key], key, value)

Example 38

View license def get_form(self, request, obj=None, **kwargs): def chose_help_text(*phrases): if next_bp: return phrases[0].format(*BS3_BREAKPOINTS[next_bp]) elif len(breakpoints) > 1: return phrases[1].format(*BS3_BREAKPOINTS[bp]) else: return phrases[2] parent_obj = self.get_parent_instance(request) if not (parent_obj and issubclass(parent_obj.plugin_class, BootstrapPluginBase)): raise ImproperlyConfigured("A BootstrapColumnPlugin requires a valid parent") glossary_fields = [] units = [ungettext_lazy("{} unit", "{} units", i).format(i) for i in range(0, 13)] breakpoints = parent_obj.get_complete_glossary()['breakpoints'] for bp in breakpoints: try: next_bp = breakpoints[breakpoints.index(bp) + 1] last = BS3_BREAKPOINT_KEYS.index(next_bp) except IndexError: next_bp = None last = None finally: first = BS3_BREAKPOINT_KEYS.index(bp) devices = ', '.join([force_text(BS3_BREAKPOINTS[b][2]) for b in BS3_BREAKPOINT_KEYS[first:last]]) if breakpoints.index(bp) == 0: # first breakpoint choices = tuple(('col-{}-{}'.format(bp, i), units[i]) for i in range(1, 13)) label = _("Column width for {}").format(devices) help_text = chose_help_text( _("Number of column units for devices narrower than {} pixels."), _("Number of column units for devices wider than {} pixels."), _("Number of column units for all devices.") ) glossary_fields.append(GlossaryField( widgets.Select(choices=choices), label=label, name='{}-column-width'.format(bp), initial='col-{}-12'.format(bp), help_text=help_text)) else: choices = (('', _("Inherit from above")),) + \ tuple(('col-{}-{}'.format(bp, i), units[i]) for i in range(1, 13)) label = _("Column width for {}").format(devices) help_text = chose_help_text( _("Override column units for devices narrower than {} pixels."), _("Override column units for devices wider than {} pixels."), _("Override column units for all devices.") ) glossary_fields.append(GlossaryField( widgets.Select(choices=choices), label=label, name='{}-column-width'.format(bp), initial='', help_text=help_text)) # handle offset if breakpoints.index(bp) == 0: empty_offset_choice = _("No offset") offset_range = range(1, 13) else: empty_offset_choice = _("Inherit from above") offset_range = range(0, 13) choices = (('', empty_offset_choice),) + \ tuple(('col-{}-offset-{}'.format(bp, i), units[i]) for i in offset_range) label = _("Offset for {}").format(devices) help_text = chose_help_text( _("Number of offset units for devices narrower than {} pixels."), _("Number of offset units for devices wider than {} pixels."), _("Number of offset units for all devices.") ) glossary_fields.append(GlossaryField( widgets.Select(choices=choices), label=label, name='{}-column-offset'.format(bp), help_text=help_text)) # handle column ordering using push/pull settings choices = (('', _("No reordering")),) + \ tuple(('col-{}-push-{}'.format(bp, i), _("Push {}").format(units[i])) for i in range(0, 12)) + \ tuple(('col-{}-pull-{}'.format(bp, i), _("Pull {}").format(units[i])) for i in range(0, 12)) label = _("Column ordering for {0}").format(devices) help_text = chose_help_text( _("Column ordering for devices narrower than {} pixels."), _("Column ordering for devices wider than {} pixels."), _("Column ordering for all devices.") ) glossary_fields.append(GlossaryField( widgets.Select(choices=choices), label=label, name='{}-column-ordering'.format(bp), help_text=help_text)) # handle responsive utilies choices = (('', _("Default")), ('visible-{}'.format(bp), _("Visible")), ('hidden-{}'.format(bp), _("Hidden")),) label = _("Responsive utilities for {}").format(devices) help_text = chose_help_text( _("Utility classes for showing and hiding content by devices narrower than {} pixels."), _("Utility classes for showing and hiding content by devices wider than {} pixels."), _("Utility classes for showing and hiding content for all devices.") ) glossary_fields.append(GlossaryField( widgets.RadioSelect(choices=choices), label=label, name='{}-responsive-utils'.format(bp), initial='', help_text=help_text)) glossary_fields = [ glossary_fields[i + len(glossary_fields) // len(breakpoints) * j] for i in range(0, len(glossary_fields) // len(breakpoints)) for j in range(0, len(breakpoints)) ] kwargs.update(glossary_fields=glossary_fields) return super(BootstrapColumnPlugin, self).get_form(request, obj, **kwargs)

Example 39

View license 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))

Example 40

View license def get_form(self, request, obj=None, **kwargs): def chose_help_text(*phrases): if next_bp: return phrases[0].format(*BS3_BREAKPOINTS[next_bp]) elif len(breakpoints) > 1: return phrases[1].format(*BS3_BREAKPOINTS[bp]) else: return phrases[2] parent_obj = self.get_parent_instance(request) if not (parent_obj and issubclass(parent_obj.plugin_class, BootstrapPluginBase)): raise ImproperlyConfigured("A BootstrapColumnPlugin requires a valid parent") glossary_fields = [] units = [ungettext_lazy("{} unit", "{} units", i).format(i) for i in range(0, 13)] breakpoints = parent_obj.get_complete_glossary()['breakpoints'] for bp in breakpoints: try: next_bp = breakpoints[breakpoints.index(bp) + 1] last = BS3_BREAKPOINT_KEYS.index(next_bp) except IndexError: next_bp = None last = None finally: first = BS3_BREAKPOINT_KEYS.index(bp) devices = ', '.join([force_text(BS3_BREAKPOINTS[b][2]) for b in BS3_BREAKPOINT_KEYS[first:last]]) if breakpoints.index(bp) == 0: # first breakpoint choices = tuple(('col-{}-{}'.format(bp, i), units[i]) for i in range(1, 13)) label = _("Column width for {}").format(devices) help_text = chose_help_text( _("Number of column units for devices narrower than {} pixels."), _("Number of column units for devices wider than {} pixels."), _("Number of column units for all devices.") ) glossary_fields.append(GlossaryField( widgets.Select(choices=choices), label=label, name='{}-column-width'.format(bp), initial='col-{}-12'.format(bp), help_text=help_text)) else: choices = (('', _("Inherit from above")),) + \ tuple(('col-{}-{}'.format(bp, i), units[i]) for i in range(1, 13)) label = _("Column width for {}").format(devices) help_text = chose_help_text( _("Override column units for devices narrower than {} pixels."), _("Override column units for devices wider than {} pixels."), _("Override column units for all devices.") ) glossary_fields.append(GlossaryField( widgets.Select(choices=choices), label=label, name='{}-column-width'.format(bp), initial='', help_text=help_text)) # handle offset if breakpoints.index(bp) == 0: empty_offset_choice = _("No offset") offset_range = range(1, 13) else: empty_offset_choice = _("Inherit from above") offset_range = range(0, 13) choices = (('', empty_offset_choice),) + \ tuple(('col-{}-offset-{}'.format(bp, i), units[i]) for i in offset_range) label = _("Offset for {}").format(devices) help_text = chose_help_text( _("Number of offset units for devices narrower than {} pixels."), _("Number of offset units for devices wider than {} pixels."), _("Number of offset units for all devices.") ) glossary_fields.append(GlossaryField( widgets.Select(choices=choices), label=label, name='{}-column-offset'.format(bp), help_text=help_text)) # handle column ordering using push/pull settings choices = (('', _("No reordering")),) + \ tuple(('col-{}-push-{}'.format(bp, i), _("Push {}").format(units[i])) for i in range(0, 12)) + \ tuple(('col-{}-pull-{}'.format(bp, i), _("Pull {}").format(units[i])) for i in range(0, 12)) label = _("Column ordering for {0}").format(devices) help_text = chose_help_text( _("Column ordering for devices narrower than {} pixels."), _("Column ordering for devices wider than {} pixels."), _("Column ordering for all devices.") ) glossary_fields.append(GlossaryField( widgets.Select(choices=choices), label=label, name='{}-column-ordering'.format(bp), help_text=help_text)) # handle responsive utilies choices = (('', _("Default")), ('visible-{}'.format(bp), _("Visible")), ('hidden-{}'.format(bp), _("Hidden")),) label = _("Responsive utilities for {}").format(devices) help_text = chose_help_text( _("Utility classes for showing and hiding content by devices narrower than {} pixels."), _("Utility classes for showing and hiding content by devices wider than {} pixels."), _("Utility classes for showing and hiding content for all devices.") ) glossary_fields.append(GlossaryField( widgets.RadioSelect(choices=choices), label=label, name='{}-responsive-utils'.format(bp), initial='', help_text=help_text)) glossary_fields = [ glossary_fields[i + len(glossary_fields) // len(breakpoints) * j] for i in range(0, len(glossary_fields) // len(breakpoints)) for j in range(0, len(breakpoints)) ] kwargs.update(glossary_fields=glossary_fields) return super(BootstrapColumnPlugin, self).get_form(request, obj, **kwargs)

Example 41

View license 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))

Example 42

View license def __init__(self, attrs=None): widget_list = [CascadingSizeWidget(), widgets.Select(choices=self.BORDER_STYLES), widgets.TextInput(attrs={'style': 'width: 5em;', 'type': 'color'})] super(SetBorderWidget, self).__init__(widget_list)

Example 43

View license def __init__(self, attrs=None): widget_list = [CascadingSizeWidget(), widgets.Select(choices=self.BORDER_STYLES), widgets.TextInput(attrs={'style': 'width: 5em;', 'type': 'color'})] super(SetBorderWidget, self).__init__(widget_list)

Example 44

View licensedef PopulatedFormFactory(request, cls, form=forms.ModelForm): model_field_names = [_.name for _ in cls._meta.get_fields()] class PopulatedForm(form): 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 get_clean_function(name): def func(self): value = None field = self.fields[name] if isinstance(field, forms.models.ModelChoiceField): related_model = field.queryset.model value = related_model.objects.get(id=request.GET[name]) else: value = request.GET[name] return value return func for key in [key for key in request.GET if key in model_field_names]: setattr(PopulatedForm, 'clean_%s' % key, get_clean_function(key)) return PopulatedForm

Example 45

View license def __init__(self, *args, **kwargs): super(VariantDataForm, self).__init__(*args, **kwargs) self.fields["template"].widget = SelectImage(choices=PRODUCT_TEMPLATES) self.fields["active_base_price"].widget = Select(choices=CHOICES)

Example 46

View licensedef PopulatedFormFactory(request, cls, form=forms.ModelForm): model_field_names = [_.name for _ in cls._meta.get_fields()] class PopulatedForm(form): 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 get_clean_function(name): def func(self): value = None field = self.fields[name] if isinstance(field, forms.models.ModelChoiceField): related_model = field.queryset.model value = related_model.objects.get(id=request.GET[name]) else: value = request.GET[name] return value return func for key in [key for key in request.GET if key in model_field_names]: setattr(PopulatedForm, 'clean_%s' % key, get_clean_function(key)) return PopulatedForm

Example 47

View license def _compute_sub_classes(self): """ Computes the choice tuple of available sub classes for this widget. """ _subclasses = [] _instance = self.rel.to() for _cls in _instance.__class__.__subclasses__(): _subclass = _cls() data_type = _subclass.__class__.__name__.lower() type_name = _subclass.__schema_name__ if type_name == "STRINGMODEL": type_name = _subclass.__class__.__name__ type_name = type_name[0:type_name.find('String_model')] _subclasses.append((data_type, type_name)) _choices = [('', 'Create new ...')] _choices.extend(_subclasses) if len(_choices) == 1: raise AssertionError('No sub classes found for {}?'.format( _instance.__class__.__name__)) _subclass_select = widgets.Select(choices=_choices) return _subclass_select, _subclasses

Example 48

View license def _compute_sub_classes(self): """ Computes the choice tuple of available sub classes for this widget. """ _subclasses = [] _instance = self.rel.to() for _cls in _instance.__class__.__subclasses__(): _subclass = _cls() data_type = _subclass.__class__.__name__.lower() type_name = _subclass.__schema_name__ if type_name == "STRINGMODEL": type_name = _subclass.__class__.__name__ type_name = type_name[0:type_name.find('String_model')] _subclasses.append((data_type, type_name)) _choices = [('', 'Create new ...')] _choices.extend(_subclasses) if len(_choices) == 1: raise AssertionError('No sub classes found for {}?'.format( _instance.__class__.__name__)) _subclass_select = widgets.Select(choices=_choices) return _subclass_select, _subclasses

Example 49

View license def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name day_choices = [(i, i) for i in range(1, 32)] if not (self.required and value): day_choices.insert(0, self.none_value) local_attrs = self.build_attrs(id=self.day_field % id_) s = Select(choices=day_choices) select_html = s.render(self.day_field % name, day_val, local_attrs) output.append(select_html) month_choices = MONTHS.items() if not (self.required and value): month_choices.append(self.none_value) month_choices.sort() local_attrs['id'] = self.month_field % id_ s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) year_choices = [(i, i) for i in self.years] if not (self.required and value): year_choices.insert(0, self.none_value) local_attrs['id'] = self.year_field % id_ s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(select_html) return mark_safe(u'\n'.join(output))

Example 50

View license def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] output = [] if 'id' in self.attrs: id_ = self.attrs['id'] else: id_ = 'id_%s' % name day_choices = [(i, i) for i in range(1, 32)] if not (self.required and value): day_choices.insert(0, self.none_value) local_attrs = self.build_attrs(id=self.day_field % id_) s = Select(choices=day_choices) select_html = s.render(self.day_field % name, day_val, local_attrs) output.append(select_html) month_choices = MONTHS.items() if not (self.required and value): month_choices.append(self.none_value) month_choices.sort() local_attrs['id'] = self.month_field % id_ s = Select(choices=month_choices) select_html = s.render(self.month_field % name, month_val, local_attrs) output.append(select_html) year_choices = [(i, i) for i in self.years] if not (self.required and value): year_choices.insert(0, self.none_value) local_attrs['id'] = self.year_field % id_ s = Select(choices=year_choices) select_html = s.render(self.year_field % name, year_val, local_attrs) output.append(select_html) return mark_safe(u'\n'.join(output))
Sours: https://programtalk.com/python-examples/django.forms.widgets.Select/
Django Dependent Drop Down List Example - Integration with Django Forms and Django Form Validations

.

Similar news:

.



664 665 666 667 668