Python django.forms.RadioSelect() Examples
The following are 30
code examples of django.forms.RadioSelect().
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 also want to check out all available functions/classes of the module
django.forms
, or try the search function
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: forms.py From conf_site with MIT License | 7 votes |
def __init__(self, *args, **kwargs): super(ProposalVoteForm, self).__init__(*args, **kwargs) # Use a radio select widget instead of a dropdown for the score. self.fields["score"] = forms.TypedChoiceField( choices=ProposalVote.SCORES, coerce=int, empty_value=0, widget=forms.RadioSelect(), )
Example #2
Source File: mc.py From coursys with GNU General Public License v3.0 | 6 votes |
def get_entry_field(self, questionanswer=None, student=None): options = self.version.config.get('options', []) permute = self.version.config.get('permute', 'keep') show_no_answer = self.version.config.get('show_no_answer', 'noshow') if questionanswer: initial = questionanswer.answer.get('data', MultipleChoice.NA) else: initial = MultipleChoice.NA options = list(enumerate(options)) # keep original positions so the input values match that, but students see a possibly-randomized order if student and permute == 'permute': rand = self.question.quiz.random_generator(str(student.id) + '-' + str(self.question.id) + '-' + str(self.version.id)) options = rand.permute(options) elif student and permute == 'not-last': rand = self.question.quiz.random_generator(str(student.id) + '-' + str(self.question.id) + '-' + str(self.version.id)) last = options[-1] options = rand.permute(options[:-1]) options.append(last) choices = [ (OPTION_LETTERS[opos], mark_safe('<span class="mc-letter">' + OPTION_LETTERS[i] + '.</span> ') + escape(o[0])) for i, (opos, o) in enumerate(options) ] if show_no_answer == 'show': choices.append((MultipleChoice.NA, 'no answer')) field = forms.ChoiceField(required=False, initial=initial, choices=choices, widget=forms.RadioSelect()) field.widget.attrs.update({'class': 'multiple-choice'}) return field
Example #3
Source File: test_radioselect.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_constructor_attrs(self): """ Attributes provided at instantiation are passed to the constituent inputs. """ widget = RadioSelect(attrs={'id': 'foo'}, choices=self.beatles) html = """ <ul id="foo"> <li> <label for="foo_0"><input checked type="radio" id="foo_0" value="J" name="beatle"> John</label> </li> <li><label for="foo_1"><input type="radio" id="foo_1" value="P" name="beatle"> Paul</label></li> <li><label for="foo_2"><input type="radio" id="foo_2" value="G" name="beatle"> George</label></li> <li><label for="foo_3"><input type="radio" id="foo_3" value="R" name="beatle"> Ringo</label></li> </ul> """ self.check_html(widget, 'beatle', 'J', html=html)
Example #4
Source File: test_radioselect.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_constructor_attrs(self): """ Attributes provided at instantiation are passed to the constituent inputs. """ widget = RadioSelect(attrs={'id': 'foo'}, choices=self.beatles) html = """ <ul id="foo"> <li> <label for="foo_0"><input checked type="radio" id="foo_0" value="J" name="beatle"> John</label> </li> <li><label for="foo_1"><input type="radio" id="foo_1" value="P" name="beatle"> Paul</label></li> <li><label for="foo_2"><input type="radio" id="foo_2" value="G" name="beatle"> George</label></li> <li><label for="foo_3"><input type="radio" id="foo_3" value="R" name="beatle"> Ringo</label></li> </ul> """ self.check_html(widget, 'beatle', 'J', html=html)
Example #5
Source File: forms.py From registrasion with Apache License 2.0 | 6 votes |
def set_fields(cls, category, products): choices = [] for product in products: choice_text = "%s -- $%d" % (product.name, product.price) choices.append((product.id, choice_text)) if not category.required: choices.append((0, "No selection")) cls.base_fields[cls.FIELD] = forms.TypedChoiceField( label=category.name, widget=forms.RadioSelect, choices=choices, empty_value=0, coerce=int, )
Example #6
Source File: forms.py From jorvik with GNU General Public License v3.0 | 6 votes |
def populate_questions_inputs(self, survey, question_group_id, **kwargs): questions_qs = survey.get_questions().filter( question_group__id=question_group_id ).order_by('order',) for question in questions_qs: if not question.is_active: # skip inactive questions continue qid = question.qid self.fields[qid] = forms.CharField(label=question.text) if question.question_type == Question.RADIO: self.fields[qid].widget = forms.RadioSelect(choices=self.CHOICES_1_10) elif question.question_type == Question.BOOLEAN: self.fields[qid] = forms.BooleanField(label=question.text) elif question.question_type == Question.TEXT: pass # non modifica niente
Example #7
Source File: models.py From wagtail-personalisation with MIT License | 6 votes |
def __init__(self, *args, **kwargs): Segment.panels = [ MultiFieldPanel([ FieldPanel('name', classname="title"), FieldRowPanel([ FieldPanel('status'), FieldPanel('persistent'), ]), FieldPanel('match_any'), FieldPanel('type', widget=forms.RadioSelect), FieldPanel('count', classname='count_field'), FieldPanel('randomisation_percent', classname='percent_field'), ], heading="Segment"), MultiFieldPanel([ RulePanel( "{}_related".format(rule_model._meta.db_table), label='{}{}'.format( rule_model._meta.verbose_name, ' ({})'.format(_('Static compatible')) if rule_model.static else '' ), ) for rule_model in AbstractBaseRule.__subclasses__() ], heading=_("Rules")), ] super(Segment, self).__init__(*args, **kwargs)
Example #8
Source File: forms.py From telemetry-analysis-service with Mozilla Public License 2.0 | 6 votes |
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) user_sshkeys = self.created_by.created_sshkeys.all() self.fields["ssh_key"].queryset = user_sshkeys.all() self.fields["ssh_key"].help_text = ( "The SSH key to deploy to the cluster. " 'See <a href="%s">your keys</a> or ' '<a href="%s">add a new one</a>.' % (reverse("keys-list"), reverse("keys-new")) ) # if the user is not a cluster maintainer, reset the max # to the default so they can't create larger clusters if not self.created_by.has_perm("clusters.maintain_cluster"): max_size = settings.AWS_CONFIG["MAX_CLUSTER_SIZE"] self.fields["size"].max_value = max_size self.fields["size"].validators.append( validators.MaxValueValidator(max_size) ) self.fields["size"].widget.attrs["max"] = max_size self.fields["size"].help_text = ( "Number of workers to use in the cluster, between 1 and %s. " "For testing or development 1 is recommended." % max_size ) # if there are fewer options we just show radio select buttons if user_sshkeys.count() <= 6: self.fields["ssh_key"].widget = forms.RadioSelect( choices=self.fields["ssh_key"].choices, attrs={"class": "radioset"} )
Example #9
Source File: forms.py From jorvik with GNU General Public License v3.0 | 6 votes |
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Per indicare con request.POST con che form/step stiamo lavorando self.fields['step'].initial = self.step # Risposte precedentemente salvate response_lezioni = self.survey_result.response_json['utilita_lezioni'] # for lezione in self.course.get_lezioni_precaricate(): for lezione in self.course.lezioni.all(): lezione_pk = 'lezioni_pk_%s' % lezione.pk # Crea i campi con 10 radio-button (0-10) self.fields[lezione_pk] = forms.CharField(label=lezione.nome) self.fields[lezione_pk].widget = forms.RadioSelect(choices=self.CHOICES_1_10) # Valorizzare gli input se ci sono le risposte lezione_pk_str = str(lezione.pk) if lezione_pk_str in response_lezioni: self.fields[lezione_pk].initial = response_lezioni[lezione_pk_str]
Example #10
Source File: forms.py From peering-manager with Apache License 2.0 | 6 votes |
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) custom_widgets = [forms.CheckboxInput, forms.RadioSelect] for field_name, field in self.fields.items(): if field.widget.__class__ in custom_widgets: css = field.widget.attrs.get("class", "") field.widget.attrs["class"] = " ".join( [css, "custom-control-input"] ).strip() else: css = field.widget.attrs.get("class", "") field.widget.attrs["class"] = " ".join([css, "form-control"]).strip() if field.required: field.widget.attrs["required"] = "required" if "placeholder" not in field.widget.attrs: field.widget.attrs["placeholder"] = field.label
Example #11
Source File: forms.py From jorvik with GNU General Public License v3.0 | 5 votes |
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) direttori_choices = [(i.pk, i.nome_completo) for i in self.course.direttori_corso()] self.fields['direttore'].widget = forms.RadioSelect(choices=direttori_choices) response_direttori = self.response_direttori if response_direttori and len(response_direttori) >= 1: self.fields['direttore'].initial = response_direttori[0] self.fields['step'].initial = self.step
Example #12
Source File: test_radioselect.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_render_as_subwidget(self): """A RadioSelect as a subwidget of MultiWidget.""" choices = (('', '------'),) + self.beatles self.check_html(MultiWidget([self.widget(choices=choices)]), 'beatle', ['J'], html=( """<ul> <li><label><input type="radio" name="beatle_0" value=""> ------</label></li> <li><label><input checked type="radio" name="beatle_0" value="J"> John</label></li> <li><label><input type="radio" name="beatle_0" value="P"> Paul</label></li> <li><label><input type="radio" name="beatle_0" value="G"> George</label></li> <li><label><input type="radio" name="beatle_0" value="R"> Ringo</label></li> </ul>""" ))
Example #13
Source File: djangocms_forms_tags.py From djangocms-forms with BSD 3-Clause "New" or "Revised" License | 5 votes |
def is_radioselect(field): return isinstance(field.field.widget, forms.RadioSelect)
Example #14
Source File: bootstrap.py From OpenMDM with Apache License 2.0 | 5 votes |
def is_radio(field): return isinstance(field.field.widget, forms.RadioSelect)
Example #15
Source File: test_nullbooleanfield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_nullbooleanfield_4(self): # Make sure we're compatible with MySQL, which uses 0 and 1 for its # boolean values (#9609). NULLBOOL_CHOICES = (('1', 'Yes'), ('0', 'No'), ('', 'Unknown')) class MySQLNullBooleanForm(Form): nullbool0 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES)) nullbool1 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES)) nullbool2 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES)) f = MySQLNullBooleanForm({'nullbool0': '1', 'nullbool1': '0', 'nullbool2': ''}) self.assertIsNone(f.full_clean()) self.assertTrue(f.cleaned_data['nullbool0']) self.assertFalse(f.cleaned_data['nullbool1']) self.assertIsNone(f.cleaned_data['nullbool2'])
Example #16
Source File: test_modelchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_num_queries(self): """ Widgets that render multiple subwidgets shouldn't make more than one database query. """ categories = Category.objects.all() class CategoriesForm(forms.Form): radio = forms.ModelChoiceField(queryset=categories, widget=forms.RadioSelect) checkbox = forms.ModelMultipleChoiceField(queryset=categories, widget=forms.CheckboxSelectMultiple) template = Template( '{% for widget in form.checkbox %}{{ widget }}{% endfor %}' '{% for widget in form.radio %}{{ widget }}{% endfor %}' ) with self.assertNumQueries(2): template.render(Context({'form': CategoriesForm()}))
Example #17
Source File: test_radioselect.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_render_as_subwidget(self): """A RadioSelect as a subwidget of MultiWidget.""" choices = (('', '------'),) + self.beatles self.check_html(MultiWidget([self.widget(choices=choices)]), 'beatle', ['J'], html=( """<ul> <li><label><input type="radio" name="beatle_0" value=""> ------</label></li> <li><label><input checked type="radio" name="beatle_0" value="J"> John</label></li> <li><label><input type="radio" name="beatle_0" value="P"> Paul</label></li> <li><label><input type="radio" name="beatle_0" value="G"> George</label></li> <li><label><input type="radio" name="beatle_0" value="R"> Ringo</label></li> </ul>""" ))
Example #18
Source File: forms.py From djangocms-forms with BSD 3-Clause "New" or "Revised" License | 5 votes |
def prepare_radio(self, field): field_attrs = field.build_field_attrs() widget_attrs = field.build_widget_attrs() field_attrs.update({ 'widget': forms.RadioSelect(attrs=widget_attrs), 'choices': field.get_choices(), }) return forms.ChoiceField(**field_attrs)
Example #19
Source File: test_nullbooleanfield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_nullbooleanfield_4(self): # Make sure we're compatible with MySQL, which uses 0 and 1 for its # boolean values (#9609). NULLBOOL_CHOICES = (('1', 'Yes'), ('0', 'No'), ('', 'Unknown')) class MySQLNullBooleanForm(Form): nullbool0 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES)) nullbool1 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES)) nullbool2 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES)) f = MySQLNullBooleanForm({'nullbool0': '1', 'nullbool1': '0', 'nullbool2': ''}) self.assertIsNone(f.full_clean()) self.assertTrue(f.cleaned_data['nullbool0']) self.assertFalse(f.cleaned_data['nullbool1']) self.assertIsNone(f.cleaned_data['nullbool2'])
Example #20
Source File: test_modelchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_num_queries(self): """ Widgets that render multiple subwidgets shouldn't make more than one database query. """ categories = Category.objects.all() class CategoriesForm(forms.Form): radio = forms.ModelChoiceField(queryset=categories, widget=forms.RadioSelect) checkbox = forms.ModelMultipleChoiceField(queryset=categories, widget=forms.CheckboxSelectMultiple) template = Template( '{% for widget in form.checkbox %}{{ widget }}{% endfor %}' '{% for widget in form.radio %}{{ widget }}{% endfor %}' ) with self.assertNumQueries(2): template.render(Context({'form': CategoriesForm()}))
Example #21
Source File: test_modelchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_no_extra_query_when_accessing_attrs(self): """ ModelChoiceField with RadioSelect widget doesn't produce unnecessary db queries when accessing its BoundField's attrs. """ class ModelChoiceForm(forms.Form): category = forms.ModelChoiceField(Category.objects.all(), widget=forms.RadioSelect) form = ModelChoiceForm() field = form['category'] # BoundField template = Template('{{ field.name }}{{ field }}{{ field.help_text }}') with self.assertNumQueries(1): template.render(Context({'field': field}))
Example #22
Source File: duplicates.py From helfertool with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, *args, **kwargs): self._helpers = kwargs.pop('helpers') super(MergeDuplicatesForm, self).__init__(*args, **kwargs) self.fields['helpers'] = forms.ModelChoiceField( queryset=self._helpers, widget=forms.RadioSelect(attrs={'id': 'helper'}), empty_label=None, required=True, label='')
Example #23
Source File: form_as_div.py From ctf-gameserver with ISC License | 5 votes |
def _get_css_classes(field): """ Helper function which returns the appropriate (Bootstrap) CSS classes for rendering an input field and its `<div>` container. Returns: A tuple of the form `(div_classes, field_classes, iterate_subfields, wrap_in_label)`. `iterate_subfields` is a bool indicating that the field should be rendered by iterating over its sub-fields (i.e. over itself) and wrapping them in containers with `field_classes`. This is required for multiple radios and checkboxes belonging together. `wrap_in_label` is a bool that specifies whether the input field should be placed inside the associated `<label>`, as required by Bootstrap for checkboxes. """ div_classes = [] field_classes = [] iterate_subfields = False wrap_in_label = False if field.errors: div_classes.append('has-error') widget = field.field.widget if isinstance(widget, CheckboxInput): div_classes.append('checkbox') wrap_in_label = True elif isinstance(widget, CheckboxSelectMultiple): div_classes.append('form-group') field_classes.append('checkbox') iterate_subfields = True elif isinstance(widget, RadioSelect): div_classes.append('form-group') field_classes.append('radio') iterate_subfields = True elif isinstance(widget, FileInput): pass elif isinstance(widget, MultiWidget): div_classes.append('form-group') div_classes.append('form-inline') field_classes.append('form-control') else: div_classes.append('form-group') field_classes.append('form-control') return (div_classes, field_classes, iterate_subfields, wrap_in_label)
Example #24
Source File: forms.py From open-humans with MIT License | 5 votes |
def __init__(self, *args, **kwargs): """ Add custom handling for requested_sources and override some widgets. """ super().__init__(*args, **kwargs) source_projects = DataRequestProject.objects.filter(approved=True).exclude( returned_data_description="" ) self.fields["requested_sources"].choices = [ (p.id, p.name) for p in source_projects ] self.fields["requested_sources"].widget = forms.CheckboxSelectMultiple() self.fields["requested_sources"].required = False override_fields = [ "is_study", "is_academic_or_nonprofit", "active", "request_username_access", ] # XXX: feels like a hack; ideally we could just override the widget in # the Meta class but it doesn't work (you end up with an empty option) for field in override_fields: # set the widget to a RadioSelect self.fields[field].widget = forms.RadioSelect() # filter out the empty choice self.fields[field].choices = [ choice for choice in self.fields[field].choices if choice[0] != "" ] # coerce the result to a boolean self.fields[field].coerce = lambda x: x == "True"
Example #25
Source File: test_models.py From callisto-core with GNU Affero General Public License v3.0 | 5 votes |
def test_generates_radio_button(self): field = mocks.MockQuestion(self.question.serialized).make_field() self.assertEqual(len(field.choices), 5) self.assertEqual(field.choices[4][1], "This is choice 4") self.assertIsInstance(field.widget, forms.RadioSelect)
Example #26
Source File: forms.py From Spirit with MIT License | 5 votes |
def __init__(self, poll, user=None, *args, **kwargs): super(PollVoteManyForm, self).__init__(*args, **kwargs) self.auto_id = 'id_poll_{pk}_%s'.format(pk=poll.pk) # Uniqueness "<label for=id_poll_pk_..." self.user = user self.poll = poll self.poll_choices = getattr(poll, 'choices', poll.poll_choices.unremoved()) choices = ((c.pk, mark_safe(c.description)) for c in self.poll_choices) if poll.is_multiple_choice: self.fields['choices'] = forms.MultipleChoiceField( choices=choices, widget=forms.CheckboxSelectMultiple, label=_("Poll choices") ) else: self.fields['choices'] = forms.ChoiceField( choices=choices, widget=forms.RadioSelect, label=_("Poll choices") )
Example #27
Source File: forms.py From django-radio with GNU General Public License v3.0 | 5 votes |
def __init__(self, has_recurrences, *args, **kwargs): super(DeleteScheduleForm, self).__init__(*args, **kwargs) if has_recurrences: choices = ( (self.DELETE_ONLY_THIS, 'Only this instance'), (self.DELETE_THIS_AND_FOLLOWING, 'This and all the following events'), (self.DELETE_ALL, 'All events in the series'), ) self.fields['action'] = forms.ChoiceField(choices=choices, label='', help_text='', widget=forms.RadioSelect)
Example #28
Source File: forms.py From telemetry-analysis-service with Mozilla Public License 2.0 | 5 votes |
def __init__(self, *args, **kwargs): super().__init__( label="EMR release", queryset=models.EMRRelease.objects.active().natural_sort_by_version(), required=True, empty_label=None, widget=forms.RadioSelect( attrs={"required": "required", "class": "radioset"} ), help_text=models.Cluster.EMR_RELEASE_HELP, )
Example #29
Source File: select.py From coursys with GNU General Public License v3.0 | 5 votes |
def make_entry_field(self, fieldsubmission=None): the_choices = [(k, v) for k, v in self.config.items() if k.startswith("choice_") and self.config[k]] the_choices = sorted(the_choices, key=lambda choice: (int) (re.findall(r'\d+', choice[0])[0])) c = forms.ChoiceField(required=self.config['required'], label=self.config['label'], help_text=self.config['help_text'], choices=the_choices, widget=forms.RadioSelect()) if fieldsubmission: initial=fieldsubmission.data['info'] c.initial=initial return c
Example #30
Source File: form_as_div.py From ctf-gameserver with ISC License | 4 votes |
def _get_css_classes(field): """ Helper function which returns the appropriate (Bootstrap) CSS classes for rendering an input field and its `<div>` container. Returns: A tuple of the form `(div_classes, field_classes, iterate_subfields, wrap_in_label)`. `iterate_subfields` is a bool indicating that the field should be rendered by iterating over its sub-fields (i.e. over itself) and wrapping them in containers with `field_classes`. This is required for multiple radios and checkboxes belonging together. `wrap_in_label` is a bool that specifies whether the input field should be placed inside the associated `<label>`, as required by Bootstrap for checkboxes. """ div_classes = [] field_classes = [] iterate_subfields = False wrap_in_label = False if field.errors: div_classes.append('has-error') widget = field.field.widget if isinstance(widget, CheckboxInput): div_classes.append('checkbox') wrap_in_label = True elif isinstance(widget, CheckboxSelectMultiple): div_classes.append('form-group') field_classes.append('checkbox') iterate_subfields = True elif isinstance(widget, RadioSelect): div_classes.append('form-group') field_classes.append('radio') iterate_subfields = True elif isinstance(widget, FileInput): pass elif isinstance(widget, MultiWidget): div_classes.append('form-group') div_classes.append('form-inline') field_classes.append('form-control') else: div_classes.append('form-group') field_classes.append('form-control') return (div_classes, field_classes, iterate_subfields, wrap_in_label)