django.forms.CheckboxSelectMultiple

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

42 Examples 7

Example 1

Project: coursys Source File: select.py
Function: make_entry_field
    def make_entry_field(self, fieldsubmission=None):

        the_choices = [(k, v) for k, v in self.config.iteritems() if k.startswith("choice_") and self.config[k]]
        the_choices = sorted(the_choices, key=lambda choice: (int) (re.findall(r'\d+', choice[0])[0]))

        initial = []

        if fieldsubmission:
            initial=fieldsubmission.data['info']

        c = self.CustomMultipleChoiceField(required=self.config['required'],
            label=self.config['label'],
            help_text=self.config['help_text'],
            choices=the_choices,
            widget=forms.CheckboxSelectMultiple(),
            initial=initial)

        return c

Example 2

Project: cartridge Source File: forms.py
    def __new__(cls, name, bases, attrs):
        for option in settings.SHOP_OPTION_TYPE_CHOICES:
            field = forms.MultipleChoiceField(label=option[1],
                required=False, widget=forms.CheckboxSelectMultiple)
            attrs["option%s" % option[0]] = field
        args = (cls, name, bases, attrs)
        return super(ProductAdminFormMetaclass, cls).__new__(*args)

Example 3

Project: wagtail Source File: forms.py
    def create_checkboxes_field(self, field, options):
        options['choices'] = [(x.strip(), x.strip()) for x in field.choices.split(',')]
        options['initial'] = [x.strip() for x in field.default_value.split(',')]
        return django.forms.MultipleChoiceField(
            widget=django.forms.CheckboxSelectMultiple, **options
        )

Example 4

Project: django-autoreports Source File: fields.py
    def extra_wizard_fields(self):
        prefix, field_name = parsed_field_name(self.field_name)
        prefix = SEPARATED_FIELD.join(prefix)
        fields = get_fields_from_model(self.model, adaptors=(TextFieldReportField,))
        current_field_name = self.field_name.split(SEPARATED_FIELD)[-1]
        choices = [(f['name'], f['verbose_name']) for f in fields[0] if f['name'] != current_field_name]
        if not choices:
            return {}
        initial = None
        if self.instance:
            field_options = self.instance.options.get(self.field_name, None)
            if field_options:
                initial = field_options.get('other_fields', None)
        return {'other_fields': forms.MultipleChoiceField(label=_('Other fields to filter'),
                                                    required=False,
                                                    choices=choices,
                                                    widget=forms.CheckboxSelectMultiple,
                                                    initial=initial,
                                                    help_text=_('Choose other fields, when you filter with this field, you will search in these also'))}

Example 5

Project: django-autoreports Source File: forms.py
Function: init
    def __init__(self, *args, **kwargs):
        super(ReportDisplayForm, self).__init__(*args, **kwargs)
        choices = [(field_name, unicode(field.label)) for field_name, field in self.fields.items()]
        self.fields = {}
        self.fields = {'__report_display_fields_choices': forms.MultipleChoiceField(
                                                            label=_('Report display fields'),
                                                            widget=forms.CheckboxSelectMultiple(),
                                                            choices=choices,
                                                            initial=dict(choices).keys(),
                                                            required=False)}

Example 6

Project: RGT-tool Source File: forms.py
    def __init__(self, *args, **kwargs):
        super(WhichGridsForm, self).__init__(*args, **kwargs)
        if len(self.data) > 0:
            choices2 = ()
            self.num_grids = self.data['num-grids']
            user_name = self.data['user']
            user1 = User.objects.filter(username=user_name)
            gridtype = Grid.GridType.USER_GRID
            templateData = ShowGridsData()
            templateData.grids = Grid.objects.filter(user=user1, grid_type=gridtype)
            for grid in templateData.grids:
                gridUsid = grid.usid
                gridName = grid.name
                dummy1 = (str(gridUsid), str(gridName))
                choices2 = (dummy1,) + choices2
            self.fields['gridChoices'] = forms.MultipleChoiceField(required=False, choices=choices2, widget=forms.CheckboxSelectMultiple)

Example 7

Project: jeeves Source File: forms.py
    def __init__(self, possible_reviewers, default_conflict_reviewers, *args, **kwargs):
        super(SubmitForm, self).__init__(*args, **kwargs)

        choices = []
        for r in possible_reviewers:
            choices.append((r.username, r))

        self.fields['conflicts'] = MultipleChoiceField(widget=CheckboxSelectMultiple(), required=False, choices=choices, initial=list(default_conflict_reviewers))

Example 8

Project: djangocms-forms Source File: forms.py
    def prepare_checkbox_multiple(self, field):
        field_attrs = field.build_field_attrs()
        widget_attrs = field.build_widget_attrs()

        field_attrs.update({
            'widget': forms.CheckboxSelectMultiple(attrs=widget_attrs),
            'choices': field.get_choices(),
        })

        if field.initial:
            field_attrs.update({
                'initial': self.split_choices(field.initial)
            })
        return forms.MultipleChoiceField(**field_attrs)

Example 9

Project: django-mongoengine Source File: djangoflavor.py
    def formfield(self, **kwargs):
        if self.field.choices:
            defaults = {
                'choices': self.field.choices,
                'widget': forms.CheckboxSelectMultiple,
                'form_class': forms.MultipleChoiceField,
            }
        elif isinstance(self.field, fields.ReferenceField):
            defaults = {
                'form_class': formfields.DocuementMultipleChoiceField,
                'queryset': self.field.docuement_type.objects,
            }
        else:
            return None
        defaults.update(kwargs)
        return super(ListField, self).formfield(**defaults)

Example 10

Project: airmozilla Source File: forms.py
Function: init
    def __init__(self, *args, **kwargs):
        super(GroupEditForm, self).__init__(*args, **kwargs)
        self.fields['name'].required = True
        choices = self.fields['permissions'].choices
        self.fields['permissions'] = forms.MultipleChoiceField(
            choices=choices,
            widget=forms.CheckboxSelectMultiple,
            required=False
        )

Example 11

Project: Spirit Source File: forms.py
Function: init
    def __init__(self, topic, *args, **kwargs):
        super(CommentMoveForm, self).__init__(*args, **kwargs)
        self.fields['comments'] = forms.ModelMultipleChoiceField(
            queryset=Comment.objects.filter(topic=topic),
            widget=forms.CheckboxSelectMultiple
        )

Example 12

Project: microformats Source File: forms.py
Function: init
    def __init__(self, *args, **kwargs): 
        super(AdrForm, self).__init__(*args, **kwargs) 
        self.fields['types'].widget = forms.CheckboxSelectMultiple()
        self.fields['types'].label = _('Address Type')
        self.fields['types'].help_text = _('Please select as many that apply')
        self.fields['types'].queryset = adr_type.objects.all()

Example 13

Project: microformats Source File: forms.py
Function: init
    def __init__(self, *args, **kwargs): 
        super(EmailForm, self).__init__(*args, **kwargs) 
        self.fields['types'].widget = forms.CheckboxSelectMultiple()
        self.fields['types'].label = _('Email Type')
        self.fields['types'].help_text = _('Please select as many that apply')
        self.fields['types'].queryset = email_type.objects.all()

Example 14

Project: microformats Source File: forms.py
Function: init
    def __init__(self, *args, **kwargs): 
        super(TelForm, self).__init__(*args, **kwargs) 
        self.fields['types'].widget = forms.CheckboxSelectMultiple()
        self.fields['types'].label = _('Telephone Type')
        self.fields['types'].help_text = _('Please select as many that apply')
        self.fields['types'].queryset = tel_type.objects.all()

Example 15

Project: logtacts Source File: forms.py
    def __init__(self, *args, **kwargs):
        super(ReviewUserForm, self).__init__(*args, **kwargs)
        queryset = User.objects.filter(is_active=False)
        choices = [
            (
                user.id,
                "{}: registered with {} on {}".format(
                    user.username,
                    user.email,
                    user.date_joined,
                )
            ) for user in queryset
        ]

        self.fields['users'] = forms.MultipleChoiceField(
            required=False,
            choices=choices,
            widget=forms.CheckboxSelectMultiple()
        )

Example 16

Project: pretix Source File: mail.py
Function: export_form_fields
    @property
    def export_form_fields(self):
        return OrderedDict(
            [
                ('status',
                 forms.MultipleChoiceField(
                     label=_('Filter by status'),
                     initial=[Order.STATUS_PENDING, Order.STATUS_PAID],
                     choices=Order.STATUS_CHOICE,
                     widget=forms.CheckboxSelectMultiple,
                     required=False
                 )),
            ]
        )

Example 17

Project: pretix Source File: item.py
    def __init__(self, **kwargs):
        items = kwargs['items']
        del kwargs['items']
        instance = kwargs.get('instance', None)
        self.original_instance = copy.copy(instance) if instance else None
        super().__init__(**kwargs)

        if hasattr(self, 'instance') and self.instance.pk:
            active_items = set(self.instance.items.all())
            active_variations = set(self.instance.variations.all())
        else:
            active_items = set()
            active_variations = set()

        for item in items:
            if len(item.variations.all()) > 0:
                self.fields['item_%s' % item.id] = ModelMultipleChoiceField(
                    label=_("Activate for"),
                    required=False,
                    initial=active_variations,
                    queryset=item.variations.all(),
                    widget=forms.CheckboxSelectMultiple
                )
            else:
                self.fields['item_%s' % item.id] = BooleanField(
                    label=_("Activate"),
                    required=False,
                    initial=(item in active_items)
                )

Example 18

Project: pretix Source File: exporters.py
Function: export_form_fields
    @property
    def export_form_fields(self):
        return OrderedDict(
            [
                ('items',
                 forms.ModelMultipleChoiceField(
                     queryset=self.event.items.all(),
                     label=_('Limit to products'),
                     widget=forms.CheckboxSelectMultiple,
                     initial=self.event.items.filter(admission=True)
                 )),
                ('secrets',
                 forms.BooleanField(
                     label=_('Include QR-code secret'),
                     required=False
                 )),
                ('paid_only',
                 forms.BooleanField(
                     label=_('Only paid orders'),
                     initial=True,
                     required=False
                 )),
                ('sort',
                 forms.ChoiceField(
                     label=_('Sort by'),
                     initial='name',
                     choices=(
                         ('name', _('Attendee name')),
                         ('code', _('Order code')),
                     ),
                     widget=forms.RadioSelect,
                     required=False
                 )),
                ('questions',
                 forms.ModelMultipleChoiceField(
                     queryset=self.event.questions.all(),
                     label=_('Include questions'),
                     widget=forms.CheckboxSelectMultiple,
                     required=False
                 )),
            ]
        )

Example 19

Project: pretix Source File: exporters.py
    @property
    def export_form_fields(self):
        return OrderedDict(
            [
                ('status',
                 forms.MultipleChoiceField(
                     label=_('Filter by status'),
                     initial=[Order.STATUS_PAID],
                     choices=Order.STATUS_CHOICE,
                     widget=forms.CheckboxSelectMultiple,
                     required=False
                 )),
                ('sort',
                 forms.ChoiceField(
                     label=_('Sort by'),
                     initial='datetime',
                     choices=(
                         ('datetime', _('Order date')),
                         ('payment_date', _('Payment date')),
                     ),
                     widget=forms.RadioSelect,
                     required=False
                 )),
            ]
        )

Example 20

Project: pretix Source File: forms.py
    def __init__(self, *args, **kwargs):
        event = kwargs.pop('event')
        super().__init__(*args, **kwargs)
        self.fields['subject'] = I18nFormField(
            widget=I18nTextInput, required=True,
            langcodes=event.settings.get('locales')
        )
        self.fields['message'] = I18nFormField(
            widget=I18nTextarea, required=True,
            langcodes=event.settings.get('locales'),
            help_text=_("Available placeholders: {due_date}, {event}, {order}, {order_date}, {order_url}")
        )
        choices = list(Order.STATUS_CHOICE)
        if not event.settings.get('payment_term_expire_automatically', as_type=bool):
            choices.append(
                ('overdue', _('pending with payment overdue'))
            )
        self.fields['sendto'] = forms.MultipleChoiceField(
            label=_("Send to"), widget=forms.CheckboxSelectMultiple,
            choices=choices
        )

Example 21

Project: handy Source File: fields.py
Function: form_field
    def formfield(self, **kwargs):
        if self.choices:
            # Also copy-pasted from Field.formfield
            defaults = {
                'choices': self.choices,
                'coerce': self.coerce,
                'required': not self.blank,
                'label': capfirst(self.verbose_name),
                'help_text': self.help_text,
                'widget': forms.CheckboxSelectMultiple
            }
            defaults.update(kwargs)
            return TypedMultipleChoiceField(**defaults)
        else:
            defaults = {
                'form_class': TypedMultipleField,
                'coerce': self.coerce,
                'widget': CommaSeparatedInput,
            }
            defaults.update(kwargs)
            return super(ArrayField, self).formfield(**defaults)

Example 22

Project: portal Source File: forms.py
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        community = kwargs.pop('community')
        super(PermissionGroupsForm, self).__init__(*args, **kwargs)

        # get all community groups and remove community admin group
        # from the list of choices
        self.groups = list(get_groups(community.name))
        admin_group = Group.objects.get(
            name=COMMUNITY_ADMIN.format(community.name))
        self.groups.remove(admin_group)
        choices = [(group.pk, group.name) for group in self.groups]
        self.fields['groups'] = forms.\
            MultipleChoiceField(choices=choices, label="", required=False,
                                widget=forms.CheckboxSelectMultiple)
        self.member_groups = self.user.get_member_groups(self.groups)
        self.fields['groups'].initial = [group.pk for group in
                                         self.member_groups]

        self.helper = SubmitCancelFormHelper(
            self, cancel_href="{% url 'community_users' community.slug %}")

Example 23

Project: tendenci Source File: forms.py
    def __init__(self, *args, **kwargs):
        super(ModelSearchForm, self).__init__(*args, **kwargs)

        # Check to see if users should be included in global search
        include_users = False

        if kwargs['user'].profile.is_superuser or get_setting('module', 'users', 'allowanonymoususersearchuser') \
        or (kwargs['user'].is_authenticated() and get_setting('module', 'users', 'allowusersearch')):
            include_users = True

        if include_users:
            for app in registered_apps:
                if app['verbose_name'].lower() == 'user':
                    registered_apps_models.append(app['model'])
                    registered_apps_names.append(app['model']._meta.model_name)
        else:
            for app in registered_apps:
                if app['verbose_name'].lower() == 'user':
                    try:
                        models_index = registered_apps_models.index(app['model'])
                        registered_apps_models.pop(models_index)
                        names_index = registered_apps_names.index(app['model']._meta.model_name)
                        registered_apps_names.pop(names_index)
                    except Exception as e:
                        pass

        self.models = registered_apps_models
        self.fields['models'] = forms.MultipleChoiceField(choices=model_choices(), required=False, label=_('Search In'), widget=forms.CheckboxSelectMultiple)

Example 24

Project: wagtail Source File: forms.py
Function: init
    def __init__(self, *args, **kwargs):
        super(PageViewRestrictionForm, self).__init__(*args, **kwargs)

        self.fields['groups'].widget = forms.CheckboxSelectMultiple()
        self.fields['groups'].queryset = Group.objects.all()

Example 25

Project: avos Source File: form_helpers.py
Function: is_multiple_checkbox
@register.filter
def is_multiple_checkbox(field):
    return isinstance(field.field.widget, django.forms.CheckboxSelectMultiple)

Example 26

Project: iCQA Source File: forms.py
    def __init__(self, set, data=None, unsaved=None, *args, **kwargs):
        initial = dict([(setting.name, setting.value) for setting in set])

        if unsaved:
            initial.update(unsaved)

        super(SettingsSetForm, self).__init__(data, initial=initial, *args, **kwargs)

        for setting in set:
            widget = setting.field_context.get('widget', None)

            if widget is forms.CheckboxSelectMultiple or widget is forms.SelectMultiple or isinstance(widget, forms.SelectMultiple):
                field = forms.MultipleChoiceField(**setting.field_context)
            elif widget is forms.RadioSelect or isinstance(widget, forms.RadioSelect):
                field = forms.ChoiceField(**setting.field_context)
            elif isinstance(setting, (Setting.emulators.get(str, DummySetting), Setting.emulators.get(unicode, DummySetting))):
                if not setting.field_context.get('widget', None):
                    setting.field_context['widget'] = forms.TextInput(attrs={'class': 'longstring'})
                field = forms.CharField(**setting.field_context)
            elif isinstance(setting, Setting.emulators.get(float, DummySetting)):
                field = forms.FloatField(**setting.field_context)
            elif isinstance(setting, Setting.emulators.get(int, DummySetting)):
                field = forms.IntegerField(**setting.field_context)
            elif isinstance(setting, Setting.emulators.get(bool, DummySetting)):
                field = forms.BooleanField(**setting.field_context)
            else:
                field = UnfilteredField(**setting.field_context)

            self.fields[setting.name] = field

        self.set = set

Example 27

Project: django-crispy-forms Source File: crispy_forms_field.py
Function: is_checkbox_select_multiple
@register.filter
def is_checkboxselectmultiple(field):
    return isinstance(field.field.widget, forms.CheckboxSelectMultiple)

Example 28

Project: django-haystack Source File: forms.py
Function: init
    def __init__(self, *args, **kwargs):
        super(ModelSearchForm, self).__init__(*args, **kwargs)
        self.fields['models'] = forms.MultipleChoiceField(choices=model_choices(), required=False, label=_('Search In'), widget=forms.CheckboxSelectMultiple)

Example 29

Project: satchmo Source File: forms.py
    def __init__(self, *args, **kwargs):
        self.optionkeys = []
        self.variationkeys = []
        self.existing = {}
        self.optiondict = {}
        self.edit_urls = {}
        self.namedict = {}
        self.skudict = {}
        self.slugdict = {}

        self.product = kwargs.pop('product', None)

        super(VariationManagerForm, self).__init__(*args, **kwargs)

        if self.product:
            configurableproduct = self.product.configurableproduct;

            for grp in configurableproduct.option_group.all():
                optchoices = [("%i_%i" % (opt.option_group.id, opt.id), opt.name) for opt in grp.option_set.all()]
                kw = {
                    'label' : grp.name,
                    'widget' : forms.CheckboxSelectMultiple(),
                    'required' : False,
                    'choices' : optchoices,
                }
                fld = forms.MultipleChoiceField(**kw)
                key = 'optiongroup__%s' % grp.id
                self.fields[key] = fld
                self.optionkeys.append(key)
                self.optiondict[grp.id] = []

            configurableproduct.setup_variation_cache()
            for opts in configurableproduct.get_all_options():
                variation = configurableproduct.get_product_from_options(opts)
                optnames = [opt.value for opt in opts]
                kw = {
                    'initial' : None,
                    'label' : " ".join(optnames),
                    'required' : False
                }

                opt_str = '__'.join(["%i_%i" % (opt.option_group.id, opt.id) for opt in opts])

                key = "pv__%s" % opt_str

                if variation:
                    basename = variation.name
                    sku = variation.sku
                    slug = variation.slug
                    kw['initial'] = 'add'
                    self.existing[key] = True
                    self.edit_urls[key] = urlresolvers.reverse('admin:product_product_change',
                                                               args=(variation.id,))
                else:
                    basename = u'%s (%s)' % (self.product.name, u'/'.join(optnames))
                    slug = slugify(u'%s_%s' % (self.product.slug, u'_'.join(optnames)))
                    sku = ""

                pv = forms.BooleanField(**kw)

                self.fields[key] = pv

                for opt in opts:
                    self.optiondict[opt.option_group.id].append(key)

                self.variationkeys.append(key)

                # Name Field

                nv = forms.CharField(initial=basename)
                namekey = "name__%s" % opt_str
                self.fields[namekey] = nv
                self.namedict[key] = namekey

                # SKU Field

                sv = forms.CharField(initial=sku, required=False)
                skukey = "sku__%s" % opt_str
                self.fields[skukey] = sv
                self.skudict[key] = skukey

                # Slug Field
                sf = forms.CharField(initial=slug)
                slugkey = "slug__%s" % opt_str
                self.fields[slugkey] = sf
                self.slugdict[key] = slugkey

Example 30

Project: editorsnotes-server Source File: projects.py
def make_project_permissions_formset(project):
    roles = project.roles.all()
    project_perms= get_all_project_permissions().order_by('content_type')

    class ProjectRoleFormSet(BaseModelFormSet):
        def __init__(self, *args, **kwargs):
            kwargs['queryset'] = roles
            super(ProjectRoleFormSet, self).__init__(*args, **kwargs)

    class ProjectRoleForm(ModelForm):
        permissions = forms.ModelMultipleChoiceField(
            required=False,
            queryset=project_perms,
            widget=forms.CheckboxSelectMultiple)
        class Meta:
            model = ProjectRole
            fields = ('role', 'permissions',)
        def __init__(self, *args, **kwargs):
            super(ProjectRoleForm, self).__init__(*args, **kwargs)
            if self.instance and self.instance.is_super_role:
                self.fields['permissions'].widget.attrs['readonly'] = True
                self.fields['permissions'].widget.attrs['checked'] = True
            elif self.instance and self.instance.id:
                self.fields['permissions'].initial = self.instance.group.permissions.all()
        def save(self, *args, **kwargs):
            # We are NOT committing the change here, because we only save the
            # form if the object already exists. This is because it was
            # difficult to deal with the M2M relations (permissions => the new
            # group which is created along with the project role) when doing
            # that. We are calling save, however, to bound this form to an
            # instance if it exists, so that we can proceed in the right way
            # afterwards (create a ProjectRole manually if no existing instance;
            # save form otherwise).
            kwargs['commit'] = False
            obj = super(ProjectRoleForm, self).save(*args, **kwargs)

            perms = self.cleaned_data['permissions']
            if not obj.id:
                new_role = ProjectRole.objects.create_project_role(
                    project, self.cleaned_data['role'])
                new_role.group.permissions.add(*perms)
            else:
                obj.save()
                obj.group.permissions.clear()
                obj.group.permissions.add(*perms)
            return obj

    formset = modelformset_factory(ProjectRole,
                                   formset=ProjectRoleFormSet,
                                   form=ProjectRoleForm,
                                   can_delete=True,
                                   extra=1)
    formset.all_perms = project_perms
    return formset

Example 31

Project: djep Source File: forms.py
    def __init__(self, *args, **kwargs):
        assert 'instance' in kwargs, 'instance is required.'

        super(TicketNameForm, self).__init__(
            prefix='tn-%s' % kwargs['instance'].pk, *args, **kwargs)

        self.fields['first_name'].required = True
        self.fields['last_name'].required = True
        self.fields['organisation'].required = False
        self.fields['dietary_preferences'] = forms.ModelMultipleChoiceField(
            label=mark_safe(pgettext('nameform', 'Dietary preferences')),
            queryset=DietaryPreference.objects.all(),
            required=False,
            widget=forms.CheckboxSelectMultiple
        )
        if 'dietary_preferences' in kwargs['instance'].related_data:
            self.initial['dietary_preferences'] = [obj.pk for obj in kwargs['instance'].related_data.get('dietary_preferences', [])]
        self.fields['shirtsize'].queryset = self.fields['shirtsize']\
            .queryset.filter(conference=current_conference())
        self.fields['shirtsize'].help_text = _('''Sizing charts: <a href="http://maxnosleeves.spreadshirt.com/shop/info/producttypedetails/Popup/Show/productType/813" target="_blank">Women</a>, <a href="http://maxnosleeves.spreadshirt.com/shop/info/producttypedetails/Popup/Show/productType/812" target="_blank">Men</a>''')

Example 32

Project: form_designer Source File: admin.py
Function: init
    def __init__(self, *args, **kwargs):
        super(FormAdminForm, self).__init__(*args, **kwargs)

        choices = (
            (key, cfg.get('title', key))
            for key, cfg in self._meta.model.CONFIG_OPTIONS)

        self.fields['config_options'] = forms.MultipleChoiceField(
            choices=choices,
            label=_('Options'),
            help_text=_('Save and continue editing to configure options.'),
            widget=forms.CheckboxSelectMultiple,
        )

        config_fieldsets = []

        try:
            selected = self.data.getlist('config_options')
        except AttributeError:
            if self.instance.pk:
                selected = self.instance.config.keys()
            else:
                selected = None

        selected = selected or ()
        self.fields['config_options'].initial = selected

        for s in selected:
            cfg = dict(self._meta.model.CONFIG_OPTIONS)[s]

            fieldset = [
                _('Form configuration: %s') % cfg.get('title', s),
                {'fields': [], 'classes': ('form-designer',)},
            ]

            for k, f in cfg.get('form_fields', []):
                self.fields['%s_%s' % (s, k)] = f
                if k in self.instance.config.get(s, {}):
                    f.initial = self.instance.config[s].get(k)
                fieldset[1]['fields'].append('%s_%s' % (s, k))

            config_fieldsets.append(fieldset)

        self.request._formdesigner_config_fieldsets = config_fieldsets

Example 33

Project: django-widgy Source File: models.py
Function: widget_class
    @property
    def widget_class(self):
        return self.WIDGET_CLASSES.get(self.type, forms.CheckboxSelectMultiple)

Example 34

Project: hellolily Source File: forms.py
    def __init__(self, *args, **kwargs):
        self.message_type = kwargs.pop('message_type', 'reply')
        super(ComposeEmailForm, self).__init__(*args, **kwargs)

        # Only show the checkbox for existing attachments if we have a pk and if we forward.
        if 'initial' in kwargs and 'draft_pk' in kwargs['initial'] and self.message_type == 'forward':
            existing_attachment_list = EmailAttachment.objects.filter(
                message_id=kwargs['initial']['draft_pk'],
                inline=False
            )
            choices = [(attachment.id, attachment.name) for attachment in existing_attachment_list]
            self.fields['existing_attachments'] = forms.MultipleChoiceField(
                choices=choices,
                widget=forms.CheckboxSelectMultiple,
                initial=[a.id for a in existing_attachment_list],
                required=False,
            )

        self.fields['template'].queryset = EmailTemplate.objects.order_by('name')

        user = get_current_user()
        self.email_accounts = EmailAccount.objects.filter(
            Q(owner=user) |
            Q(shared_with_users=user) |
            Q(public=True)
        ).filter(tenant=user.tenant, is_deleted=False).distinct('id')

        # Only provide choices you have access to
        self.fields['send_from'].choices = [(email_account.id, email_account) for email_account in self.email_accounts]
        self.fields['send_from'].empty_label = None

        # Set user's primary_email as default choice if there is no initial value
        initial_email_account = self.initial.get('send_from', None)
        if not initial_email_account:
            if user.primary_email_account:
                initial_email_account = user.primary_email_account.id
            else:
                for email_account in self.email_accounts:
                    if email_account.email_address == user.email:
                        initial_email_account = email_account
                        break
        elif isinstance(initial_email_account, basestring):
            for email_account in self.email_accounts:
                if email_account.email == initial_email_account:
                    initial_email_account = email_account
                    break

        self.initial['send_from'] = initial_email_account

Example 35

Project: pybbm Source File: forms.py
    def __init__(self, user, *args, **kwargs):

        """
        Creates the form to grant moderator privileges, checking if the request user has the
        permission to do so.

        :param user: request user
        """

        super(ModeratorForm, self).__init__(*args, **kwargs)
        categories = Category.objects.all()
        self.authorized_forums = []
        if not permissions.perms.may_manage_moderators(user):
            raise PermissionDenied()
        for category in categories:
            forums = [forum.pk for forum in category.forums.all() if permissions.perms.may_change_forum(user, forum)]
            if forums:
                self.authorized_forums += forums
                self.fields['cat_%d' % category.pk] = forms.ModelMultipleChoiceField(
                    label=category.name,
                    queryset=category.forums.filter(pk__in=forums),
                    widget=forms.CheckboxSelectMultiple(),
                    required=False
                )

Example 36

Project: philo Source File: __init__.py
Function: form_field
	def formfield(self, **kwargs):
		# This is necessary because django hard-codes TypedChoiceField for things with choices.
		defaults = {
			'widget': forms.CheckboxSelectMultiple,
			'choices': self.get_choices(include_blank=False),
			'label': capfirst(self.verbose_name),
			'required': not self.blank,
			'help_text': self.help_text
		}
		if self.has_default():
			if callable(self.default):
				defaults['initial'] = self.default
				defaults['show_hidden_initial'] = True
			else:
				defaults['initial'] = self.get_default()
		
		for k in kwargs.keys():
			if k not in ('coerce', 'empty_value', 'choices', 'required',
						 'widget', 'label', 'initial', 'help_text',
						 'error_messages', 'show_hidden_initial'):
				del kwargs[k]
		
		defaults.update(kwargs)
		form_class = forms.TypedMultipleChoiceField
		return form_class(**defaults)

Example 37

Project: django-mongodbforms Source File: fieldgenerator.py
    def generate_listfield(self, field, **kwargs):
        # We can't really handle embedded docuements here.
        # So we just ignore them
        if isinstance(field.field, MongoEmbeddedDocuementField):
            return
        
        defaults = {
            'label': self.get_field_label(field),
            'help_text': self.get_field_help_text(field),
            'required': field.required,
        }
        if field.field.choices:
            map_key = 'listfield_choices'
            defaults.update({
                'choices': field.field.choices,
                'widget': forms.CheckboxSelectMultiple
            })
        elif isinstance(field.field, MongoReferenceField):
            map_key = 'listfield_references'
            defaults.update({
                'queryset': field.field.docuement_type.objects.clone(),
            })
        else:
            map_key = 'listfield'
            form_field = self.generate(field.field)
            defaults.update({
                'contained_field': form_field.__class__,
            })
        form_class = self.form_field_map.get(map_key)
        defaults.update(self.check_widget(map_key))
        defaults.update(kwargs)
        return form_class(**defaults)

Example 38

Project: softwarecollections Source File: forms.py
Function: init
    def __init__(self, *args, **kwargs):
        super(ReposForm, self).__init__(*args, **kwargs)
        self.current_repos = dict(
            ('{}/{}/{}'.format(repo.copr.username, repo.copr.name, repo.name), repo)
            for repo in self.instance.all_repos
        )
        self.available_repos = {}
        self.fields['repos'].choices = []
        for copr in self.instance.all_coprs:
            label   = '{} / {}'.format(copr.username, copr.name)
            choices = []
            for name, url in sorted(copr.yum_repos.items()):
                slug = '{}/{}'.format(copr.slug, name)
                if slug in self.current_repos:
                    repo = self.current_repos[slug]
                else:
                    repo = Repo(
                        slug     = '{}/{}'.format(self.instance.slug, name),
                        scl      = self.instance,
                        copr     = copr,
                        name     = name,
                        copr_url = url,
                    )
                choices.append((
                    slug,
                    mark_safe('<img src="{}" width="32" height="32" alt=""/> {} {} {}'.format(
                        repo.get_icon_url(), repo.distro.title(), repo.version, repo.arch
                    )),
                ))
                self.available_repos[slug] = repo
            self.fields['repos'].choices.append((label, choices))
        self.initial['repos'] = self.current_repos.keys()
        self.fields['other_repos'].widget = forms.CheckboxSelectMultiple(
            renderer = CheckboxSelectMultipleTableRenderer,
            choices  = [
                (
                    repo.id,
                    mark_safe('<img src="{}" width="32" height="32" alt=""/> {}'.format(
                        repo.get_icon_url(), repo,
                    )),
                ) for repo in self.fields['other_repos'].widget.choices.queryset
            ],
        )

Example 39

Project: django-hstore-flattenfields Source File: fields.py
Function: init
    def __init__(self, *args, **kwargs):
        self.widget = forms.CheckboxSelectMultiple(
            attrs=kwargs.pop('html_attrs', {})
        )
        super(HstoreCheckboxInput, self).__init__(*args, **kwargs)

Example 40

Project: Spirit Source File: forms.py
    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 41

Project: Spirit Source File: forms.py
Function: init
    def __init__(self, user=None, poll=None, *args, **kwargs):
        super(TopicPollVoteManyForm, self).__init__(*args, **kwargs)
        self.user = user
        self.poll = poll
        choices = TopicPollChoice.objects.filter(poll=poll)

        if poll.is_multiple_choice:
            self.fields['choices'] = forms.ModelMultipleChoiceField(
                queryset=choices,
                widget=forms.CheckboxSelectMultiple,
                label=_("Poll choices")
            )
        else:
            self.fields['choices'] = forms.ModelChoiceField(
                queryset=choices,
                widget=forms.RadioSelect,
                label=_("Poll choices"),
                empty_label=None
            )

        self.fields['choices'].label_from_instance = lambda obj: smart_text(obj.description)

Example 42

Project: OpenMDM Source File: bootstrap.py
Function: is_multiple_checkbox
@register.filter
def is_multiple_checkbox(field):
    return isinstance(field.field.widget, forms.CheckboxSelectMultiple)