django.forms.ModelMultipleChoiceField

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

30 Examples 7

Example 1

Project: talk.org Source File: related.py
Function: form_field
    def formfield(self, **kwargs):
        defaults = {'form_class': forms.ModelMultipleChoiceField, 'queryset': self.rel.to._default_manager.all()}
        defaults.update(kwargs)
        # If initial is passed in, it's a list of related objects, but the
        # MultipleChoiceField takes a list of IDs.
        if defaults.get('initial') is not None:
            defaults['initial'] = [i._get_pk_val() for i in defaults['initial']]
        return super(ManyToManyField, self).formfield(**defaults)

Example 2

Project: djangae Source File: related.py
Function: form_field
    def formfield(self, **kwargs):
        db = kwargs.pop('using', None)
        defaults = {
            'form_class': forms.ModelMultipleChoiceField,
            'queryset': self.rel.to._default_manager.using(db).complex_filter(self.rel.limit_choices_to)
        }
        defaults.update(kwargs)
        # If initial is passed in, it's a list of related objects, but the
        # MultipleChoiceField takes a list of IDs.
        if defaults.get('initial') is not None:
            initial = defaults['initial']
            if callable(initial):
                initial = initial()
            defaults['initial'] = [i._get_pk_val() for i in initial]
        return super(RelatedIteratorField, self).formfield(**defaults)

Example 3

Project: pretix Source File: questions.py
    def _save_to_answer(self, field, answer, value):
        if isinstance(field, forms.ModelMultipleChoiceField):
            answstr = ", ".join([str(o) for o in value])
            if not answer.pk:
                answer.save()
            else:
                answer.options.clear()
            answer.answer = answstr
            answer.options.add(*value)
        elif isinstance(field, forms.ModelChoiceField):
            if not answer.pk:
                answer.save()
            else:
                answer.options.clear()
            answer.options.add(value)
            answer.answer = value.answer
        else:
            answer.answer = value

Example 4

Project: django-shop Source File: product.py
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == 'cms_pages':
            # restrict many-to-many field for cms_pages to ProductApp only
            limit_choices_to = {'publisher_is_draft': False, 'application_urls': 'ProductsListApp'}
            queryset = Page.objects.filter(**limit_choices_to)
            widget = admin.widgets.FilteredSelectMultiple(_("CMS Pages"), False)
            field = forms.ModelMultipleChoiceField(queryset=queryset, widget=widget)
            return field
        return super(CMSPageAsCategoryMixin, self).formfield_for_manytomany(db_field, request, **kwargs)

Example 5

Project: shuup Source File: product_list_modifiers.py
    def get_fields(self, request, category=None):
        if not Category.objects.exists():
            return

        language = get_language()
        base_queryset = Category.objects.all_visible(request.customer, request.shop, language=language)
        if category:
            queryset = base_queryset.filter(shop_products__categories=category).exclude(pk=category.pk).distinct()
        else:
            # Show only first level when there is no category selected
            queryset = base_queryset.filter(parent=None)

        return [
            (
                "categories",
                forms.ModelMultipleChoiceField(
                    queryset=queryset, required=False, label=_('Categories'), widget=FilterWidget())
            ),
        ]

Example 6

Project: shuup Source File: plugins.py
    def populate(self):
        """
        A custom populate method to display page choices
        """
        for field in self.plugin.fields:
            if isinstance(field, tuple):
                name, value = field
                value.initial = self.plugin.config.get(name, value.initial)
                self.fields[name] = value
        self.fields["pages"] = forms.ModelMultipleChoiceField(
            queryset=Page.objects.visible(),
            required=False,
            initial=self.plugin.config.get("pages", None),
        )

Example 7

Project: shuup Source File: category_links.py
    def populate(self):
        """
        A custom populate method to display category choices
        """
        for field in self.plugin.fields:
            if isinstance(field, tuple):
                name, value = field
                value.initial = self.plugin.config.get(name, value.initial)
                self.fields[name] = value
        self.fields["categories"] = forms.ModelMultipleChoiceField(
            queryset=Category.objects.all_visible(customer=None),
            required=False,
            initial=self.plugin.config.get("categories", None),
        )

Example 8

Project: shuup Source File: test_bootstrap_field_renderer.py
def test_field_title_quoting():
    with translation.override("en"):
        field = forms.ModelMultipleChoiceField(queryset=User.objects.all(), help_text="Something about \"Control\"")
        field.choices = []  # Don't bother with database stuff
        assert "\"Control\"" in force_text(field.help_text)
        form = forms.Form()
        form.fields["field1"] = field
        form.fields["field2"] = forms.CharField(label="An Unrelated Field")
        assert ""Control"" in force_text(AdminFieldRenderer(form["field1"]).render())
        assert "title=\"\"" not in force_text(AdminFieldRenderer(form["field2"]).render())

Example 9

Project: jaikuenginepatch Source File: dbutils.py
Function: get_form_field
    def get_form_field(self, **kwargs):
        from django import forms
        defaults = {'form_class': forms.ModelMultipleChoiceField,
                    'queryset': self.reference_class.all(),
                    'required': False}
        defaults.update(kwargs)
        return super(KeyListProperty, self).get_form_field(**defaults)

Example 10

Project: transifex Source File: forms.py
    def __init__(self, project, user, *args, **kwargs):
        super(ReleaseForm, self).__init__(*args, **kwargs)
        projects = self.fields["project"].queryset.filter(slug=project.slug)
        self.fields["project"].queryset = projects
        self.fields["project"].empty_label = None
        self.user = user

        if not project.is_hub:
            queryset = Resource.objects.filter(project=project)
            self.fields["resources"] = forms.ModelMultipleChoiceField(
                queryset=queryset, required=True, 
                help_text=_('Select the resources to add to the Release. '
                    'Once this project is not a Project Hub, it is only '
                    'possible to choose resources that belong to this '
                    'project.'))

Example 11

Project: doc-versions Source File: admin.py
Function: get_form
    def get_form(self, request, obj=None, **kwargs):
        form = super(DocuementModelAdmin, self).get_form(request, obj, **kwargs)
        for _, field in form.base_fields.iteritems():
            if isinstance(field, forms.ModelMultipleChoiceField) and \
                    issubclass(field.queryset.model, Docuement):
                now = datetime.now()
                field.queryset = field.queryset.filter(
                    docuement_start__lte=now, docuement_end__gt=now)
        return form

Example 12

Project: django-compositepks Source File: related.py
Function: form_field
    def formfield(self, **kwargs):
        defaults = {'form_class': forms.ModelMultipleChoiceField, 'queryset': self.rel.to._default_manager.complex_filter(self.rel.limit_choices_to)}
        defaults.update(kwargs)
        # If initial is passed in, it's a list of related objects, but the
        # MultipleChoiceField takes a list of IDs.
        if defaults.get('initial') is not None:
            defaults['initial'] = [i._get_pk_val() for i in defaults['initial']]
        return super(ManyToManyField, self).formfield(**defaults)

Example 13

Project: netbox Source File: views.py
Function: get_form
    def get_form(self):
        """Provide a standard bulk delete form if none has been specified for the view"""

        class BulkDeleteForm(ConfirmationForm):
            pk = ModelMultipleChoiceField(queryset=self.cls.objects.all(), widget=MultipleHiddenInput)

        if self.form:
            return self.form
        return BulkDeleteForm

Example 14

Project: philo Source File: base.py
Function: value_formfields
	def value_formfields(self):
		field = self._meta.get_field('content_type')
		fields = {field.name: field.formfield(initial=getattr(self.content_type, 'pk', None))}
		
		if self.content_type:
			kwargs = {
				'initial': self.object_ids,
				'required': False,
				'queryset': self.content_type.model_class()._default_manager.all()
			}
			fields['value'] = forms.ModelMultipleChoiceField(**kwargs)
		return fields

Example 15

Project: airmozilla Source File: forms.py
Function: init
    def __init__(self, *args, **kwargs):
        super(SavedSearchForm, self).__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].required = False
            if isinstance(self.fields[field], forms.ModelMultipleChoiceField):
                self.fields[field].help_text = ''

Example 16

Project: popcorn_maker Source File: forms.py
Function: init
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(ProjectEditForm, self).__init__(*args, **kwargs)
        queryset = (ProjectCategory.objects
                    .filter(projectcategorymembership__user=user,
                            projectcategorymembership__status=ProjectCategoryMembership.APPROVED))
        self.has_categories = True if queryset else False
        self.fields.update({
            'categories': forms.ModelMultipleChoiceField(queryset=queryset,
                                                         required=False,
                                                         widget=CheckboxSelectMultiple)
                                                         })

Example 17

Project: theyworkforyou Source File: related.py
Function: form_field
    def formfield(self, **kwargs):
        defaults = {'form_class': forms.ModelMultipleChoiceField, 'queryset': self.rel.to._default_manager.complex_filter(self.rel.limit_choices_to)}
        defaults.update(kwargs)
        # If initial is passed in, it's a list of related objects, but the
        # MultipleChoiceField takes a list of IDs.
        if defaults.get('initial') is not None:
            initial = defaults['initial']
            if callable(initial):
                initial = initial()
            defaults['initial'] = [i._get_pk_val() for i in initial]
        return super(ManyToManyField, self).formfield(**defaults)

Example 18

Project: theyworkforyou Source File: related.py
Function: form_field
    def formfield(self, **kwargs):
        # If initial is passed in, it's a list of related objects, but the
        # MultipleChoiceField takes a list of IDs.
        if kwargs.get('initial') is not None:
            kwargs['initial'] = [i._get_pk_val() for i in kwargs['initial']]
        defaults = {'queryset' : self.rel.to._default_manager.all(), 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text}
        defaults.update(kwargs)
        return forms.ModelMultipleChoiceField(**defaults)

Example 19

Project: pretix Source File: item.py
Function: init
    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 20

Project: shuup Source File: product_list_modifiers.py
Function: get_fields
    def get_fields(self, request, category=None):
        if not Manufacturer.objects.exists():
            return
        if category:
            manufacturer_ids = set(
                ShopProduct.objects.filter(
                    categories__in=[category]).values_list("product__manufacturer__pk", flat=True).distinct()
            )
            if manufacturer_ids == set([None]):
                return
            queryset = Manufacturer.objects.filter(pk__in=manufacturer_ids)
        else:
            queryset = Manufacturer.objects.all()
        return [
            (
                "manufacturers",
                forms.ModelMultipleChoiceField(
                    queryset=queryset, required=False, label=_('Manufacturers'), widget=FilterWidget())
            ),
        ]

Example 21

Project: wger Source File: exercises.py
    def get_form_class(self):

        # Define the exercise form here because only at this point during the request
        # have we access to the currently used language. In other places Django defaults
        # to 'en-us'.
        class ExerciseForm(ModelForm):
            category = ModelChoiceField(queryset=ExerciseCategory.objects.all(),
                                        widget=TranslatedSelect())
            muscles = ModelMultipleChoiceField(queryset=Muscle.objects.all(),
                                               widget=TranslatedOriginalSelectMultiple(),
                                               required=False)

            muscles_secondary = ModelMultipleChoiceField(queryset=Muscle.objects.all(),
                                                         widget=TranslatedOriginalSelectMultiple(),
                                                         required=False)

            class Meta:
                model = Exercise
                widgets = {'equipment': TranslatedSelectMultiple()}
                fields = ['name_original',
                          'category',
                          'description',
                          'muscles',
                          'muscles_secondary',
                          'equipment',
                          'license',
                          'license_author']

            class Media:
                js = ('/static/bower_components/tinymce/tinymce.min.js',)

        return ExerciseForm

Example 22

Project: django-autoreports Source File: fields.py
Function: get_basic_field_form
    def get_basic_field_form(self, form, field_name):
        return forms.ModelMultipleChoiceField(label=self.get_verbose_name(),
                                        queryset=self.field.model.objects.all())

Example 23

Project: Adlibre-DMS Source File: representator.py
def create_form_fields(plugins_param = ''):
    """
    Generator of form fields in desired grouping.
    
    Takes Plugin model queryset or produces own from all plugins.
    
    Makes:
    - getting all plugins queryset if not given
    - getting used plugins types and cleaning them to disable repeating of them
    - grouping fields for PluginSelectorForm 
    
    Returns kwargs dictionary with form fields to populate form.
    """
    # getting all plugins queryset if not given
    if plugins_param == '':
        plugins = Plugin.objects.all()
    else:
        plugins = plugins_param
    # init
    all_plugins_types = []
    plugin_types_clean = []
    plugins_done = []
    kwargs = {}
    # getting used plugins types and cleaning them to disable repeating of them
    for plugin in plugins:
        plugin_temp = plugin.get_plugin()
        plugin_temp.pk = plugin.pk
        plugins_done.append(plugin_temp)
        all_plugins_types.append(plugin_temp.plugin_type)
        # appending all unique types to types list
        if not (plugin_temp.plugin_type in plugin_types_clean):
            plugin_types_clean.append(plugin_temp.plugin_type)
    
    # grouping fields for PluginSelectorForm
    for plugin_type in plugin_types_clean:
        plugins_temp_list = []
        for plugin in plugins_done:
            if plugin.plugin_type == plugin_type:
                #add plugin to current plugins list
                plugins_temp_list.append(plugin.pk)
        #saving plugins list to main dict
        kwargs[plugin_type] = forms.ModelMultipleChoiceField(plugins.filter(pk__in = plugins_temp_list))
    return kwargs

Example 24

Project: django-oscar Source File: forms.py
def _attr_multi_option_field(attribute):
    return forms.ModelMultipleChoiceField(
        label=attribute.name,
        required=attribute.required,
        queryset=attribute.option_group.options.all())

Example 25

Project: ocf Source File: views.py
def flowspace(request, slice_id, fsmode = 'advanced', free_vlan = None, alertMessage=""):
    """
    Add flowspace.
    """
    slice = get_object_or_404(Slice, id=slice_id)

    class SliverMultipleChoiceField(forms.ModelMultipleChoiceField):
        def label_from_instance(self, obj):
            return "%s" % obj.resource.as_leaf_class()

        def widget_attrs(self, widget):
            return {"class": "wide"}

    def formfield_callback(f):
        if f.name == "slivers":
            return SliverMultipleChoiceField(
                queryset=OpenFlowInterfaceSliver.objects.filter(slice=slice),
                initial=OpenFlowInterfaceSliver.objects.filter(slice=slice))
        else:
            return f.formfield()

    if request.method == "POST":
        continue_to_start_slice = False
        
        # No extra forms apart from the one being shown
        flowspace_form_number = 0
        
        if fsmode == 'failed':
            # If an exception was risen from the previous step, the flowspace needs to be requested here
            flowspace_form_number = 1
        
        # create a formset to handle all flowspaces
        FSFormSet = forms.models.modelformset_factory(
            model=FlowSpaceRule,
            formfield_callback=formfield_callback,
            can_delete=True,
            extra=flowspace_form_number,
        )
        
        # Default formset
        formset = FSFormSet(
            queryset=FlowSpaceRule.objects.filter(
                slivers__slice=slice).distinct(),
        )
        if formset.is_valid():
            formset.save()

        if fsmode == 'advanced':
            formset = FSFormSet(
                request.POST,
                queryset=FlowSpaceRule.objects.filter(
                    slivers__slice=slice).distinct(),
            )
            if formset.is_valid():
                formset.save()
                continue_to_start_slice = True
        elif fsmode == 'simple':
            #create a simple flowspacerule containing only the vlans tags and the OF ports
            try:
                #create_simple_slice_vlan_based(free_vlan[0], slice)
                create_slice_with_vlan_range(slice, free_vlan)
                continue_to_start_slice = True
            except:
                #continue_to_start_slice flag will deal with this
                pass

        if continue_to_start_slice:
            slice_save_start(request, slice_id)
            if fsmode == 'simple':
                return HttpResponseRedirect(reverse("slice_detail", args=[slice_id]))
            else:
                return HttpResponseRedirect(request.path)

    elif request.method == "GET":
        flowspace_form_contents = FlowSpaceRule.objects.filter(slivers__slice=slice).distinct()
        flowspace_form_number = 1

        # When coming from the OpenFlow switches topology selection page...
        if "HTTP_REFERER" in request.META:
            # Checks if the referer page is the topology selcetion
            if reverse("book_openflow", args=[slice_id]) in request.META['HTTP_REFERER']:
                # If no flowspace has been selected yet, show an extra form to allow user to choose at least one
                if not flowspace_form_contents:
                    flowspace_form_number = 1 # Show an extra (1) form besides the already selected one
                # Otherwise, when there is some already requested flowspace, show only the requested ones (no extra forms)
                else:
                    flowspace_form_number = 0 # No extra forms apart from the one(s) being shown
        
        # Redefine formset to handle all flowspaces
        # Extra: field that determines how many extra flowspaces there are
        FSFormSet = forms.models.modelformset_factory(
            model=FlowSpaceRule,
            formfield_callback=formfield_callback,
            can_delete=True,
            extra=flowspace_form_number, # Show number of forms according to origin path request and so on
        )
        formset = FSFormSet(
            queryset=flowspace_form_contents,
        )

    else:
        return HttpResponseNotAllowed("GET", "POST")

    done = PlanetLabSliver.objects.filter(slice=slice).count() == 0

    return simple.direct_to_template(
        request,
        template="openflow_select_flowspace.html",
        extra_context={
            "slice": slice,
            "fsformset": formset,
            "alertMessage":alertMessage,
            "done": done,
            "breadcrumbs": (
                ("Home", reverse("home")),
                ("Project %s" % slice.project.name, reverse("project_detail", args=[slice.project.id])),
                ("Slice %s" % slice.name, reverse("slice_detail", args=[slice_id])),
                ("Choose Flowspace", reverse("flowspace", args=[slice_id])),
            ),
        },
    )

Example 26

Project: ocf Source File: views.py
def save_flowspace(request, slice_id):
    """
    Saves flowspace and gets back to slice detail page.
    """
    if request.method == "POST":
        slice = get_object_or_404(Slice, id=slice_id)
        
        class SliverMultipleChoiceField(forms.ModelMultipleChoiceField):
            def label_from_instance(self, obj):
                return "%s" % obj.resource.as_leaf_class()
            
            def widget_attrs(self, widget):
                return {"class": "wide"}
            
        def formfield_callback(f):
            if f.name == "slivers":
                return SliverMultipleChoiceField(
                    queryset=OpenFlowInterfaceSliver.objects.filter(slice=slice))
            else:
                return f.formfield()
        
        continue_to_start_slice = False
        
        # create a formset to handle all flowspaces
        FSFormSet = forms.models.modelformset_factory(
            model=FlowSpaceRule,
            formfield_callback=formfield_callback,
            can_delete=True,
            extra=0,
        )
        
        formset = FSFormSet(
            request.POST,
            queryset=FlowSpaceRule.objects.filter(
                slivers__slice=slice).distinct(),
        )
        if formset.is_valid():
            formset.save()
            continue_to_start_slice = True

        if continue_to_start_slice:
            slice_save_start(request, slice_id)
        
        return HttpResponseRedirect(reverse("slice_detail", args=[slice_id]))
    else:
        return HttpResponseNotAllowed("POST")

Example 27

Project: META-SHARE Source File: admin.py
Function: init
        def __init__(self, choices = None, *args, **kwargs):
            super(EditorGroupAdmin.UserProfileinEditorGroupForm, self).__init__(*args, **kwargs)
            if choices is not None:
                self.choices = choices
                self.fields['users'] = forms.ModelMultipleChoiceField(self.choices)

Example 28

Project: META-SHARE Source File: admin.py
Function: init
        def __init__(self, choices = None, *args, **kwargs):
            super(EditorGroupManagersAdmin.UserProfileinEditorGroupManagersForm, self).__init__(*args, **kwargs)
            if choices is not None:
                self.choices = choices
                self.fields['users'] = forms.ModelMultipleChoiceField(self.choices)

Example 29

Project: META-SHARE Source File: admin.py
Function: init
        def __init__(self, choices = None, *args, **kwargs):
            super(OrganizationAdmin.UserProfileinOrganizationForm, self).__init__(*args, **kwargs)
            if choices is not None:
                self.choices = choices
                self.fields['users'] = forms.ModelMultipleChoiceField(self.choices)

Example 30

Project: META-SHARE Source File: admin.py
Function: init
        def __init__(self, choices = None, *args, **kwargs):
            super(OrganizationManagersAdmin.UserProfileinOrganizationManagersForm, self).__init__(*args, **kwargs)
            if choices is not None:
                self.choices = choices
                self.fields['users'] = forms.ModelMultipleChoiceField(self.choices)