Python django.forms 模块,RadioSelect() 实例源码

我们从Python开源项目中,提取了以下33个代码示例,用于说明如何使用django.forms.RadioSelect()

项目:SuperSurvey    作者:KKhanda    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        questions = sorted(list(kwargs.pop('questions')), key=attrgetter("number"))
        super(SurveyForm, self).__init__(*args, **kwargs)

        for i, question in enumerate(questions):
            if question.type == 'MC':
                vrs = question.variants
                self.fields['question_%s' % question.id] = forms.ChoiceField(
                    label=question.text,
                    choices=[(j, vrs[j]) for j in range(len(vrs))],
                    widget=forms.RadioSelect,
                    required=True)
            elif question.type == 'NR':
                self.fields['question_%s' % question.id] = forms.ChoiceField(
                    choices=[(i, i) for i in range(1, 11)],
                    label=question.text)
            elif question.type == 'TE':
                self.fields['question_%s' % question.id] = forms.CharField(
                    max_length=512,
                    required=True,
                    widget=forms.TextInput(),
                    label=question.text)
项目:django-danceschool    作者:django-danceschool    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.add_input(Submit('submit', _('Submit')))
        user = kwargs.pop('user', None)

        if hasattr(user,'id'):
            kwargs.update(initial={
                'submissionUser': user.id
            })
        super(RevenueReportingForm,self).__init__(*args,**kwargs)
        self.fields['submissionUser'].widget = forms.HiddenInput()
        self.fields['invoiceNumber'].widget = forms.HiddenInput()
        self.fields["invoiceItem"] = InvoiceItemChoiceField(queryset=InvoiceItem.objects.none(),required=False)

        # re-order fields to put the associateWith RadioSelect first.
        newFields = OrderedDict()
        newFields['associateWith'] = self.fields['associateWith']
        for key,field in self.fields.items():
            if key not in ['associateWith']:
                newFields[key] = field
        self.fields = newFields
项目:telemetry-analysis-service    作者:mozilla    | 项目源码 | 文件源码
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 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',
                },
            )
项目:a4-meinberlin    作者:liqd    | 项目源码 | 文件源码
def __init__(self, user=None, organisation=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        choices = [(value, string)
                   for value, string in models.RECEIVER_CHOICES
                   if value != models.PLATFORM or (user and user.is_superuser)]
        self.fields['receivers'] = forms.ChoiceField(
            label=_('Receivers'),
            choices=choices,
            widget=forms.RadioSelect(),
        )

        project_qs = Project.objects
        if organisation:
            project_qs = Project.objects.filter(organisation=organisation.id)

        self.fields['project'] = forms.ModelChoiceField(
            label=_('Project'),
            queryset=project_qs,
            required=False, empty_label=None)

        self.fields['organisation'] = forms.ModelChoiceField(
            label=_('Organisation'),
            queryset=Organisation.objects,
            required=False, empty_label=None)
项目:api-django    作者:lafranceinsoumise    | 项目源码 | 文件源码
def __init__(self, *args, poll, **kwargs):
        super().__init__(*args, **kwargs)
        self.poll = poll
        self.helper = FormHelper()

        if 'options' in self.poll.rules and self.poll.rules['options'] == 1:
            self.fields['choice'] = ModelChoiceField(
                label='Choix',
                queryset=poll.options.all().order_by('?'),
                widget=RadioSelect,
                required=True,
                empty_label=None,
                initial=None,
            )
        else:
            self.fields['choice'] = ModelMultipleChoiceField(
                label='Choix',
                queryset=poll.options.all().order_by('?'),
                widget=CheckboxSelectMultiple(),
            )

        self.helper.add_input(Submit('submit', 'Confirmer'))
项目:mes    作者:osess    | 项目源码 | 文件源码
def test_custom_django_widget(self):
        class CustomRadioSelect(forms.RadioSelect):
            pass

        class CustomCheckboxSelectMultiple(forms.CheckboxSelectMultiple):
            pass

        # Make sure an inherited RadioSelect gets rendered as it
        form = CheckboxesTestForm()
        form.fields['inline_radios'].widget = CustomRadioSelect()
        form.helper = FormHelper()
        form.helper.layout = Layout('inline_radios')

        html = render_crispy_form(form)
        self.assertTrue('class="radio"' in html)

        # Make sure an inherited CheckboxSelectMultiple gets rendered as it
        form.fields['checkboxes'].widget = CustomCheckboxSelectMultiple()
        form.helper.layout = Layout('checkboxes')
        html = render_crispy_form(form)
        self.assertTrue('class="checkbox"' in html)
项目:registrasion    作者:chrisjrn    | 项目源码 | 文件源码
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,
        )
项目:django-survey-formset    作者:hamdigdoura    | 项目源码 | 文件源码
def nested_formset_factory(parent_model, child_model, grandchild_model):
    parent_child = inlineformset_factory(
        parent_model,
        child_model,
        formset=BaseNestedFormset,
        max_num=1,
        fields="__all__",
        widgets={'type': forms.RadioSelect(),
                 'text': forms.Textarea({'class': 'materialize-textarea'})
                 },
        extra=1,
        exclude=['help_text', 'order', ],
        can_order=True,
        can_delete=True,
    )

    parent_child.nested_formset_class = inlineformset_factory(
        child_model,
        grandchild_model,
        max_num=8,
        extra=4,
        validate_max=True,
        widgets={'text': forms.TextInput()},
        exclude=['ORDER', ],
        can_delete=True,
    )

    return parent_child

# The best link: http://yergler.net/blog/2009/09/27/nested-formsets-with-django/
# Nested formset
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def is_radio(field):
    return isinstance(field.field.widget, forms.RadioSelect)
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        product_classes = kwargs.pop('product_classes', [])
        super(ProductClassSelectorForm, self).__init__(*args, **kwargs)
        choices = [(obj.pk, obj.name) for obj in product_classes]
        self.fields['product_cls'] = forms.ChoiceField(
            label=pgettext_lazy('Product class form label', 'Product type'),
            choices=choices, widget=forms.RadioSelect)
项目:pyconjp-website    作者:pyconjp    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(ReviewForm, self).__init__(*args, **kwargs)
        self.fields["vote"] = forms.ChoiceField(
            widget=forms.RadioSelect(),
            choices=VOTES.CHOICES
        )
项目:opencon-2016-app-code    作者:sparcopen    | 项目源码 | 文件源码
def __init__(self, choices, *args, **kwargs):
        fields = [
            forms.ChoiceField(choices=choices, widget=forms.RadioSelect, required=False),
            forms.CharField(required=False, widget=forms.TextInput, help_text='Other')
        ]
        self.widget = OptionalChoiceWidget(widgets=[f.widget for f in fields])
        super().__init__(required=False, fields=fields, *args, **kwargs)
项目:callisto-core    作者:project-callisto    | 项目源码 | 文件源码
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)
项目:stormtrooper    作者:CompileInc    | 项目源码 | 文件源码
def __init__(self, task, *args, **kwargs):
        super(ChoiceAnswerForm, self).__init__(*args, **kwargs)
        if task:
            qs = task.choices
            widget = forms.RadioSelect
            empty_label = None
            count = task.no_of_choices
            if count > settings.TASK_CHOICE_SELECT_CUTOFF:
                widget = forms.Select
                empty_label = BLANK_CHOICE_DASH[0][1]
            self.fields['answer'] = forms.ModelChoiceField(queryset=qs,
                                                           widget=widget,
                                                           empty_label=empty_label)
项目:wagtailsurveys    作者:torchbox    | 项目源码 | 文件源码
def test_fields(self):
        """
        This tests that all fields were added to the form with the correct types
        """
        form_class = self.fb.get_form_class()

        field_names = form_class.base_fields.keys()

        # All fields are present in form
        self.assertIn('your-name', field_names)
        self.assertIn('your-biography', field_names)
        self.assertIn('your-birthday', field_names)
        self.assertIn('your-birthtime', field_names)
        self.assertIn('your-email', field_names)
        self.assertIn('your-homepage', field_names)
        self.assertIn('your-favourite-number', field_names)
        self.assertIn('your-favourite-python-ides', field_names)
        self.assertIn('your-favourite-python-ide', field_names)
        self.assertIn('your-choices', field_names)
        self.assertIn('i-agree-to-the-terms-of-use', field_names)

        # All fields have proper type
        self.assertIsInstance(form_class.base_fields['your-name'], forms.CharField)
        self.assertIsInstance(form_class.base_fields['your-biography'], forms.CharField)
        self.assertIsInstance(form_class.base_fields['your-birthday'], forms.DateField)
        self.assertIsInstance(form_class.base_fields['your-birthtime'], forms.DateTimeField)
        self.assertIsInstance(form_class.base_fields['your-email'], forms.EmailField)
        self.assertIsInstance(form_class.base_fields['your-homepage'], forms.URLField)
        self.assertIsInstance(form_class.base_fields['your-favourite-number'], forms.DecimalField)
        self.assertIsInstance(form_class.base_fields['your-favourite-python-ides'], forms.ChoiceField)
        self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'], forms.ChoiceField)
        self.assertIsInstance(form_class.base_fields['your-choices'], forms.MultipleChoiceField)
        self.assertIsInstance(form_class.base_fields['i-agree-to-the-terms-of-use'], forms.BooleanField)

        # Some fields have non-default widgets
        self.assertIsInstance(form_class.base_fields['your-biography'].widget, forms.Textarea)
        self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'].widget, forms.RadioSelect)
        self.assertIsInstance(form_class.base_fields['your-choices'].widget, forms.CheckboxSelectMultiple)
项目:ecs    作者:ecs-org    | 项目源码 | 文件源码
def ResultField(**kwargs):
    return Vote._meta.get_field('result').formfield(widget=forms.RadioSelect(), **kwargs)
项目:wamp-polls    作者:alterway    | 项目源码 | 文件源码
def make_vote_form(cls, question):
        """Makes dynamically a new form class based on this one because form fields
        don't support context based properties
        """
        field_choices = [(choice.pk, choice.choice_text) for choice in question.choice_set.all()]
        vote_field = forms.ChoiceField(choices=field_choices, widget=forms.RadioSelect)
        return type('VoteForm', (VoteForm,), {'vote': vote_field})
项目:telemetry-analysis-service    作者:mozilla    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super().__init__(
            label='EMR release',
            queryset=models.EMRRelease.objects.active(),
            required=True,
            empty_label=None,
            widget=forms.RadioSelect(attrs={
                'required': 'required',
                'class': 'radioset',
            }),
            help_text=models.Cluster.EMR_RELEASE_HELP,
        )
项目:jiango    作者:yefei    | 项目源码 | 文件源码
def is_radio(field):
    return isinstance(field.field.widget, forms.RadioSelect)
项目:jiango    作者:yefei    | 项目源码 | 文件源码
def is_radio(field):
    return isinstance(field.field.widget, forms.RadioSelect)
项目:infonex_crm    作者:asterix135    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(PersonTerritorySelectMethodForm, self).__init__(*args, **kwargs)
        self.fields['filter_master_selects'] = forms.ChoiceField(
            choices=PERSON_MASTER_RELATION_CHOICES,
            widget=forms.RadioSelect(
                attrs={'class': 'radio-inline'}
            ),
        )
        self.fields['filter_master_selects'].label = \
            'Filter the master selects or start from scratch?'
项目:website    作者:hackerspace-ntnu    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(SettingsModelForm, self).__init__(*args, **kwargs)
        instance = kwargs.get('instance', None)
        self.__editing_instance = False
        if instance:
            self.__editing_instance = True
            self.fields['delete_subscriptions'] = ArticleSubscriptionModelMultipleChoiceField(
                models.ArticleSubscription.objects.filter(
                    subscription__settings=instance),
                label=ugettext("Remove subscriptions"),
                required=False,
                help_text=ugettext("Select article subscriptions to remove from notifications"),
                initial=models.ArticleSubscription.objects.none(),
            )
            self.fields['email'] = forms.TypedChoiceField(
                label=_("Email digests"),
                choices=(
                    (0, ugettext('Unchanged (selected on each article)')),
                    (1, ugettext('No emails')),
                    (2, ugettext('Email on any change')),
                ),
                coerce=lambda x: int(x) if x is not None else None,
                widget=forms.RadioSelect(),
                required=False,
                initial=0,
            )
项目:opencabs    作者:rtnpro    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        source = kwargs.pop('source')
        destination = kwargs.pop('destination')
        booking_type = kwargs.pop('booking_type')
        super().__init__(*args, **kwargs)
        self.fields['vehicle_type'].widget = forms.RadioSelect()
        code = settings.ROUTE_CODE_FUNC(source.name, destination.name)
        choices = []
        for rate in Rate.objects.filter(code=code):
            label = render_to_string(
                'opencabs/partials/vehicle_rate_label.html',
                context={'rate': rate, 'booking_type': booking_type})
            choices.append((rate.vehicle_category_id, label))
        self.fields['vehicle_type'].choices = choices
        self.fields['vehicle_type'].widget.attrs = {'hidden': 'true'}
项目:django-wizard-builder    作者:project-callisto    | 项目源码 | 文件源码
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)
项目:djangolg    作者:wolcomm    | 项目源码 | 文件源码
def form_factory(method=None, data=None, prefix=None):
    """Dynamically generate a form for the given LG method."""
    exceptions.check_type(instance=method, classinfo=BaseMethod)

    class FormClass(LookingGlassBaseForm):
        method_name = forms.CharField(
            required=True,
            widget=forms.HiddenInput,
            initial=method.name
        )
        auth_key = forms.CharField(
            required=True,
            widget=forms.HiddenInput,
        )
        target = method.target_field
        if method.options:
            options = forms.TypedChoiceField(
                required=True,
                choices=method.option_choices,
                widget=forms.RadioSelect(),
                initial=0,
                coerce=int,
                empty_value=None
            )
    form = FormClass(data, prefix=prefix)
    return form
项目:django-daiquiri    作者:aipescience    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)

        # add a field for each detail key
        for detail_key in settings.AUTH_DETAIL_KEYS:

            choices = [(option['id'], option['label']) for option in detail_key['options']]

            if detail_key['data_type'] == 'text':
                field = forms.CharField(widget=forms.TextInput(attrs={'placeholder': detail_key['label']}))
            elif detail_key['data_type'] == 'textarea':
                field = forms.CharField(widget=forms.Textarea(attrs={'placeholder': detail_key['label']}))
            elif detail_key['data_type'] == 'select':
                field = forms.ChoiceField(choices=choices)
            elif detail_key['data_type'] == 'radio':
                field = forms.ChoiceField(choices=choices, widget=forms.RadioSelect)
            elif detail_key['data_type'] == 'multiselect':
                field = forms.MultipleChoiceField(choices=choices)
            elif detail_key['data_type'] == 'checkbox':
                field = forms.MultipleChoiceField(choices=choices, widget=forms.CheckboxSelectMultiple)
            else:
                raise Exception('Unknown detail key data type.')

            if 'label' in detail_key:
                field.label = detail_key['label']

            if 'required' in detail_key:
                field.required = detail_key['required']

            if 'help_text' in detail_key:
                field.help_text = detail_key['help_text']

            if self.instance.details and detail_key['key'] in self.instance.details:
                field.initial = self.instance.details[detail_key['key']]

            self.fields[detail_key['key']] = field
项目:mes    作者:osess    | 项目源码 | 文件源码
def is_radioselect(field):
    return isinstance(field.field.widget, forms.RadioSelect)
项目:perdiem-django    作者:RevolutionTech    | 项目源码 | 文件源码
def __init__(self, user, *args, **kwargs):
        super(EditAvatarForm, self).__init__(*args, **kwargs)
        self.fields['avatar'] = forms.ChoiceField(
            choices=self.get_avatar_choices(user), required=False, widget=forms.RadioSelect
        )
项目:helfertool    作者:helfertool    | 项目源码 | 文件源码
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='')
项目:kanjitester    作者:larsyencken    | 项目源码 | 文件源码
def __init__(self, question):
        options = list(question.options.all())
        random.shuffle(options)
        super(QuestionField, self).__init__(
                choices=tuple([
                        (unicode(opt.id), unicode(opt.value))\
                        for opt in options
                    ]),
                widget=forms.RadioSelect,
                help_text=question.instructions,
                label=question.stimulus,
            )

# XXX could be cleaned up a bit, perhaps using suggestions from:
# http://jacobian.org/writing/dynamic-form-generation/
项目:mes    作者:osess    | 项目源码 | 文件源码
def render(self, context):
        # Nodes are not threadsafe so we must store and look up our instance
        # variables in the current rendering context first
        if self not in context.render_context:
            context.render_context[self] = (
                template.Variable(self.field),
                self.attrs,
                template.Variable(self.html5_required)
            )

        field, attrs, html5_required = context.render_context[self]
        field = field.resolve(context)
        try:
            html5_required = html5_required.resolve(context)
        except template.VariableDoesNotExist:
            html5_required = False

        widgets = getattr(field.field.widget, 'widgets', [field.field.widget])

        if isinstance(attrs, dict):
            attrs = [attrs] * len(widgets)

        for widget, attr in zip(widgets, attrs):
            class_name = widget.__class__.__name__.lower()
            class_name = class_converter.get(class_name, class_name)
            css_class = widget.attrs.get('class', '')
            if css_class:
                if css_class.find(class_name) == -1:
                    css_class += " %s" % class_name
            else:
                css_class = class_name

            if (
                TEMPLATE_PACK == 'bootstrap3'
                and not is_checkbox(field)
                and not is_file(field)
            ):
                css_class += ' form-control'

            widget.attrs['class'] = css_class

            # HTML5 required attribute
            if html5_required and field.field.required and 'required' not in widget.attrs:
                if field.field.widget.__class__.__name__ is not 'RadioSelect':
                    widget.attrs['required'] = 'required'

            for attribute_name, attribute in attr.items():
                attribute_name = template.Variable(attribute_name).resolve(context)

                if attribute_name in widget.attrs:
                    widget.attrs[attribute_name] += " " + template.Variable(attribute).resolve(context)
                else:
                    widget.attrs[attribute_name] = template.Variable(attribute).resolve(context)

        return field
项目:sasa    作者:lhmlihaomin    | 项目源码 | 文件源码
def map_field(self, cfield):
        label = cfield.title
        if cfield.required:
            suffix = "*"

        if cfield.field_type == "string":
            f = forms.CharField(required=cfield.required,
                                label=label,
                                label_suffix=suffix)
        elif cfield.field_type == "text":
            f = forms.CharField(required=cfield.required, 
                                widget=forms.Textarea, 
                                label=label,
                                label_suffix=suffix)
        elif cfield.field_type == "email":
            f = forms.EmailField(required=cfield.required, 
                                 label=label,
                                 label_suffix=suffix)
        elif cfield.field_type == "boolean":
            f = forms.BooleanField(required=cfield.required, 
                                   label=label,
                                   label_suffix=suffix)
        elif cfield.field_type == "number":
            f = forms.FloatField(required=cfield.required, 
                                 label=label,
                                 label_suffix=suffix)
        elif cfield.field_type == "integer":
            f = forms.IntegerField(required=cfield.required, 
                                   label=label,
                                   label_suffix=suffix)
        elif cfield.field_type == "select":
            f = forms.ChoiceField(required=cfield.required, 
                                  choices=cfield.choices, 
                                  label=label,
                                  label_suffix=suffix)
        elif cfield.field_type == "select_multiple":
            f = forms.MultipleChoiceField(required=cfield.required, 
                                          choices=cfield.choices, 
                                          label=label,
                                          label_suffix=suffix)
        elif cfield.field_type == "checkbox":
            f = forms.BooleanField(required=cfield.required, 
                                   label=label,
                                   label_suffix=suffix)
        elif cfield.field_type == "radio":
            f = forms.ChoiceField(required=cfield.required, 
                                  choices=cfield.choices, 
                                  widget=forms.RadioSelect, 
                                  label=label,
                                  label_suffix=suffix)
        else:
            # return a generic text input:
            f = forms.CharField()
        return f
项目:netbox    作者:digitalocean    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(BootstrapMixin, self).__init__(*args, **kwargs)

        exempt_widgets = [forms.CheckboxInput, forms.ClearableFileInput, forms.FileInput, forms.RadioSelect]

        for field_name, field in self.fields.items():
            if field.widget.__class__ not in exempt_widgets:
                css = field.widget.attrs.get('class', '')
                field.widget.attrs['class'] = ' '.join([css, 'form-control']).strip()
            if field.required and not isinstance(field.widget, forms.FileInput):
                field.widget.attrs['required'] = 'required'
            if 'placeholder' not in field.widget.attrs:
                field.widget.attrs['placeholder'] = field.label