Python django.forms.ModelMultipleChoiceField() Examples

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

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

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

Example 1
Project: mendelmd   Author: raonyguimaraes   File: forms.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, user=None, *args, **kwargs):
        
        super(ComparisonForm, self).__init__(*args, **kwargs)

        if user.is_staff:
            
            self.fields['individual_one'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.all().order_by('id'), required=False)
            self.fields['individual_two'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.all().order_by('id'), required=False)

        elif not user.is_authenticated:
            
            self.fields['individual_one'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False)
            self.fields['individual_two'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False)
        else:
            print('user', user)
            self.fields['individual_one'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False)
            self.fields['individual_two'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False) 
Example 2
Project: mendelmd   Author: raonyguimaraes   File: forms.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, user=None, *args, **kwargs):
        
        super(FamilyAnalysisForm, self).__init__(*args, **kwargs)

        if not user.is_authenticated:
            # print('user None', user)
            self.fields['mother'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False)
            self.fields['father'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False)
            self.fields['children'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False)
            self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False)
        else:
            # print('user', user)
            self.fields['mother'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False)
            self.fields['father'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False)
            self.fields['children'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False)
            self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False)


# INDIVIDUALS = [(x.id, x.name) for x in Individual.objects.all().order_by('id')] 
Example 3
Project: mendelmd   Author: raonyguimaraes   File: forms.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, user=None, *args, **kwargs):
        
        super(ComparisonForm, self).__init__(*args, **kwargs)

        if user.is_staff:
            
            self.fields['individual_one'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.all().order_by('id'), required=False)
            self.fields['individual_two'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.all().order_by('id'), required=False)

        elif not user.is_authenticated:
            
            self.fields['individual_one'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False)
            self.fields['individual_two'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False)
        else:
            print('user', user)
            self.fields['individual_one'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False)
            self.fields['individual_two'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False) 
Example 4
Project: mendelmd   Author: raonyguimaraes   File: forms.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, user=None, *args, **kwargs):
        
        super(ComparisonForm, self).__init__(*args, **kwargs)

        if user.is_staff:
            
            self.fields['individual_one'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.all().order_by('id'), required=False)
            self.fields['individual_two'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.all().order_by('id'), required=False)

        elif not user.is_authenticated:
            
            self.fields['individual_one'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False)
            self.fields['individual_two'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False)
        else:
            print('user', user)
            self.fields['individual_one'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False)
            self.fields['individual_two'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False) 
Example 5
Project: mendelmd   Author: raonyguimaraes   File: forms.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, user=None, *args, **kwargs):
        
        super(FamilyAnalysisForm, self).__init__(*args, **kwargs)

        if not user.is_authenticated:
            # print('user None', user)
            self.fields['mother'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False)
            self.fields['father'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False)
            self.fields['children'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False)
            self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False)
        else:
            # print('user', user)
            self.fields['mother'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False)
            self.fields['father'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False)
            self.fields['children'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False)
            self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=user).order_by('id'), required=False)


# INDIVIDUALS = [(x.id, x.name) for x in Individual.objects.all().order_by('id')] 
Example 6
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_model_multiple_choice_show_hidden_initial(self):
        """
        Test support of show_hidden_initial by ModelMultipleChoiceField.
        """
        class WriterForm(forms.Form):
            persons = forms.ModelMultipleChoiceField(show_hidden_initial=True, queryset=Writer.objects.all())

        person1 = Writer.objects.create(name="Person 1")
        person2 = Writer.objects.create(name="Person 2")

        form = WriterForm(initial={'persons': [person1, person2]},
                          data={'initial-persons': [str(person1.pk), str(person2.pk)],
                                'persons': [str(person1.pk), str(person2.pk)]})
        self.assertTrue(form.is_valid())
        self.assertFalse(form.has_changed())

        form = WriterForm(initial={'persons': [person1, person2]},
                          data={'initial-persons': [str(person1.pk), str(person2.pk)],
                                'persons': [str(person2.pk)]})
        self.assertTrue(form.is_valid())
        self.assertTrue(form.has_changed()) 
Example 7
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_to_field_name_with_initial_data(self):
        class ArticleCategoriesForm(forms.ModelForm):
            categories = forms.ModelMultipleChoiceField(Category.objects.all(), to_field_name='slug')

            class Meta:
                model = Article
                fields = ['categories']

        article = Article.objects.create(
            headline='Test article',
            slug='test-article',
            pub_date=datetime.date(1988, 1, 4),
            writer=Writer.objects.create(name='Test writer'),
            article='Hello.',
        )
        article.categories.add(self.c2, self.c3)
        form = ArticleCategoriesForm(instance=article)
        self.assertCountEqual(form['categories'].value(), [self.c2.slug, self.c3.slug]) 
Example 8
Project: djongo   Author: nesdis   File: test_modelchoicefield.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_disabled_multiplemodelchoicefield(self):
        class ArticleForm(forms.ModelForm):
            categories = forms.ModelMultipleChoiceField(Category.objects.all(), required=False)

            class Meta:
                model = Article
                fields = ['categories']

        category1 = Category.objects.create(name='cat1')
        category2 = Category.objects.create(name='cat2')
        article = Article.objects.create(
            pub_date=datetime.date(1988, 1, 4),
            writer=Writer.objects.create(name='Test writer'),
        )
        article.categories.set([category1.pk])

        form = ArticleForm(data={'categories': [category2.pk]}, instance=article)
        self.assertEqual(form.errors, {})
        self.assertEqual([x.pk for x in form.cleaned_data['categories']], [category2.pk])
        # Disabled fields use the value from `instance` rather than `data`.
        form = ArticleForm(data={'categories': [category2.pk]}, instance=article)
        form.fields['categories'].disabled = True
        self.assertEqual(form.errors, {})
        self.assertEqual([x.pk for x in form.cleaned_data['categories']], [category1.pk]) 
Example 9
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_to_field_name_with_initial_data(self):
        class ArticleCategoriesForm(forms.ModelForm):
            categories = forms.ModelMultipleChoiceField(Category.objects.all(), to_field_name='slug')

            class Meta:
                model = Article
                fields = ['categories']

        article = Article.objects.create(
            headline='Test article',
            slug='test-article',
            pub_date=datetime.date(1988, 1, 4),
            writer=Writer.objects.create(name='Test writer'),
            article='Hello.',
        )
        article.categories.add(self.c2, self.c3)
        form = ArticleCategoriesForm(instance=article)
        self.assertCountEqual(form['categories'].value(), [self.c2.slug, self.c3.slug]) 
Example 10
Project: djongo   Author: nesdis   File: test_modelchoicefield.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_disabled_multiplemodelchoicefield(self):
        class ArticleForm(forms.ModelForm):
            categories = forms.ModelMultipleChoiceField(Category.objects.all(), required=False)

            class Meta:
                model = Article
                fields = ['categories']

        category1 = Category.objects.create(name='cat1')
        category2 = Category.objects.create(name='cat2')
        article = Article.objects.create(
            pub_date=datetime.date(1988, 1, 4),
            writer=Writer.objects.create(name='Test writer'),
        )
        article.categories.set([category1.pk])

        form = ArticleForm(data={'categories': [category2.pk]}, instance=article)
        self.assertEqual(form.errors, {})
        self.assertEqual([x.pk for x in form.cleaned_data['categories']], [category2.pk])
        # Disabled fields use the value from `instance` rather than `data`.
        form = ArticleForm(data={'categories': [category2.pk]}, instance=article)
        form.fields['categories'].disabled = True
        self.assertEqual(form.errors, {})
        self.assertEqual([x.pk for x in form.cleaned_data['categories']], [category1.pk]) 
Example 11
Project: mendelmd   Author: raonyguimaraes   File: forms.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, user=None, *args, **kwargs):

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

        if not user.is_authenticated:
            # print('user None', user)
            self.fields['individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False, label='INDIVIDUALS')
            self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False, label='INDIVIDUALS')
        else:
            print('user', user)
            if user.is_superuser:
                self.fields['individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter().order_by('id'), required=False, label='INDIVIDUALS')
                self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter().order_by('id'), required=False, label='INDIVIDUALS')
            else:
                self.fields['individuals'] = forms.ModelMultipleChoiceField(
                    queryset=Individual.objects.filter(Q(user=user) | Q(user=None)).order_by('id'), required=False, label='INDIVIDUALS')
                self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(
                    queryset=Individual.objects.filter(Q(user=user) | Q(user=None)).order_by('id'), required=False, label='INDIVIDUALS')
        # self.fields['sift'].widget.attrs['readonly'] = True
        # self.fields['polyphen'].widget.attrs['readonly'] = True
        # self.fields['genomes1000'].widget.attrs['readonly'] = True
        # self.fields['dbsnp_frequency'].widget.attrs['readonly'] = True
        # self.fields['esp_frequency'].widget.attrs['readonly'] = True
         

#trio analysis 
Example 12
Project: mendelmd   Author: raonyguimaraes   File: forms.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, user=None, *args, **kwargs):

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

        if not user.is_authenticated:
            # print('user None', user)
            self.fields['individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False, label='INDIVIDUALS')
            self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False, label='INDIVIDUALS')
        else:
            print('user', user)
            if user.is_superuser:
                self.fields['individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter().order_by('id'), required=False, label='INDIVIDUALS')
                self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter().order_by('id'), required=False, label='INDIVIDUALS')
            else:
                self.fields['individuals'] = forms.ModelMultipleChoiceField(
                    queryset=Individual.objects.filter(Q(user=user) | Q(user=None)).order_by('id'), required=False, label='INDIVIDUALS')
                self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(
                    queryset=Individual.objects.filter(Q(user=user) | Q(user=None)).order_by('id'), required=False, label='INDIVIDUALS')
        # self.fields['sift'].widget.attrs['readonly'] = True
        # self.fields['polyphen'].widget.attrs['readonly'] = True
        # self.fields['genomes1000'].widget.attrs['readonly'] = True
        # self.fields['dbsnp_frequency'].widget.attrs['readonly'] = True
        # self.fields['esp_frequency'].widget.attrs['readonly'] = True
         

#trio analysis 
Example 13
Project: mendelmd   Author: raonyguimaraes   File: forms.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, user=None, *args, **kwargs):

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

        if not user.is_authenticated:
            # print('user None', user)
            self.fields['individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False, label='INDIVIDUALS')
            self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter(user=None).order_by('id'), required=False, label='INDIVIDUALS')
        else:
            print('user', user)
            if user.is_superuser:
                self.fields['individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter().order_by('id'), required=False, label='INDIVIDUALS')
                self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(queryset=Individual.objects.filter().order_by('id'), required=False, label='INDIVIDUALS')
            else:
                self.fields['individuals'] = forms.ModelMultipleChoiceField(
                    queryset=Individual.objects.filter(Q(user=user) | Q(user=None)).order_by('id'), required=False, label='INDIVIDUALS')
                self.fields['exclude_individuals'] = forms.ModelMultipleChoiceField(
                    queryset=Individual.objects.filter(Q(user=user) | Q(user=None)).order_by('id'), required=False, label='INDIVIDUALS')
        # self.fields['sift'].widget.attrs['readonly'] = True
        # self.fields['polyphen'].widget.attrs['readonly'] = True
        # self.fields['genomes1000'].widget.attrs['readonly'] = True
        # self.fields['dbsnp_frequency'].widget.attrs['readonly'] = True
        # self.fields['esp_frequency'].widget.attrs['readonly'] = True
         

#trio analysis 
Example 14
Project: GTDWeb   Author: lanbing510   File: related.py    License: GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        db = kwargs.pop('using', None)
        defaults = {
            'form_class': forms.ModelMultipleChoiceField,
            'queryset': self.rel.to._default_manager.using(db),
        }
        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 15
Project: kobo-predict   Author: awemulya   File: forms.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, project, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        super(SiteBulkEditForm, self).__init__(*args, **kwargs)

        self.fields['sites'] = forms.ModelMultipleChoiceField(
            widget=forms.CheckboxSelectMultiple,
            queryset=project.sites.all(),
        )

        for attr in project.site_meta_attributes:
            q_type = attr['question_type']
            q_name = attr['question_name']

            if q_type == 'Number':
                field = forms.FloatField()
            elif q_type == 'Date':
                field = forms.DateField()
            elif q_type == 'MCQ':
                options = attr.get('mcq_options') or []
                choices = [o.get('option_text') for o in options]
                choices = [(c, c) for c in choices]
                field = forms.ChoiceField(choices=choices)
            else:
                field = forms.CharField()

            self.fields[q_name] = field 
Example 16
Project: bioforum   Author: reBiocoder   File: related.py    License: MIT License 5 votes vote down vote up
def formfield(self, *, using=None, **kwargs):
        defaults = {
            'form_class': forms.ModelMultipleChoiceField,
            'queryset': self.remote_field.model._default_manager.using(using),
        }
        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.pk for i in initial]
        return super().formfield(**defaults) 
Example 17
Project: tom_base   Author: TOMToolkit   File: facility.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        if settings.TARGET_PERMISSIONS_ONLY:
            self.common_layout = Layout('facility', 'target_id', 'observation_type')
        else:
            self.fields['groups'] = forms.ModelMultipleChoiceField(Group.objects.none(),
                                                                   required=False,
                                                                   widget=forms.CheckboxSelectMultiple)
            self.common_layout = Layout('facility', 'target_id', 'observation_type', 'groups')
        self.helper.layout = Layout(
            self.common_layout,
            self.layout(),
            self.button_layout()
        ) 
Example 18
Project: tom_base   Author: TOMToolkit   File: forms.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if not settings.TARGET_PERMISSIONS_ONLY:
            self.fields['groups'] = forms.ModelMultipleChoiceField(Group.objects.none(),
                                                                   required=False,
                                                                   widget=forms.CheckboxSelectMultiple) 
Example 19
Project: SEMS   Author: urankajtazaj   File: forms.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['first_name'] = forms.ModelMultipleChoiceField(queryset=Student.objects.all())
        self.fields['first_name'].widget.attrs.update({'class': 'form-control'}) 
Example 20
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: related.py    License: MIT License 5 votes vote down vote up
def formfield(self, *, using=None, **kwargs):
        defaults = {
            'form_class': forms.ModelMultipleChoiceField,
            'queryset': self.remote_field.model._default_manager.using(using),
            **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.pk for i in initial]
        return super().formfield(**defaults) 
Example 21
Project: Spirit   Author: nitely   File: forms.py    License: MIT License 5 votes vote down vote up
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 22
Project: python   Author: Yeah-Kun   File: related.py    License: Apache License 2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        db = kwargs.pop('using', None)
        defaults = {
            'form_class': forms.ModelMultipleChoiceField,
            'queryset': self.remote_field.model._default_manager.using(db),
        }
        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 23
Project: luscan-devel   Author: blackye   File: related.py    License: GNU General Public License v2.0 5 votes vote down vote up
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(ManyToManyField, self).formfield(**defaults) 
Example 24
Project: openhgsenti   Author: drexly   File: related.py    License: Apache License 2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        db = kwargs.pop('using', None)
        defaults = {
            'form_class': forms.ModelMultipleChoiceField,
            'queryset': self.remote_field.model._default_manager.using(db),
        }
        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 25
Project: python2017   Author: bpgc-cte   File: related.py    License: MIT License 5 votes vote down vote up
def formfield(self, **kwargs):
        db = kwargs.pop('using', None)
        defaults = {
            'form_class': forms.ModelMultipleChoiceField,
            'queryset': self.remote_field.model._default_manager.using(db),
        }
        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 26
Project: graphene-django   Author: graphql-python   File: test_converter.py    License: MIT License 5 votes vote down vote up
def test_should_multiple_choice_convert_connectionorlist():
    field = forms.ModelMultipleChoiceField(queryset=None)
    graphene_type = convert_form_field(field)
    assert isinstance(graphene_type, List)
    assert graphene_type.of_type == ID 
Example 27
Project: Dailyfresh-B2C   Author: BeanWei   File: fields.py    License: Apache License 2.0 5 votes vote down vote up
def _check_values(self, value):
        null = self.null_label is not None and value and self.null_value in value
        if null:  # remove the null value and any potential duplicates
            value = [v for v in value if v != self.null_value]

        result = list(super(ModelMultipleChoiceField, self)._check_values(value))
        result += [self.null_value] if null else []
        return result 
Example 28
Project: helfertool   Author: helfertool   File: helper.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.helper = kwargs.pop('helper')
        self.user = kwargs.pop('user')

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

        event = self.helper.event

        # field that contains all shifts if
        #  - user is admin for shift/job
        #  - helper is not already in this shift

        # all administered shifts
        administered_jobs = [job for job in event.job_set.all()
                             if job.is_admin(self.user)]
        shifts = Shift.objects.filter(job__event=event,
                                      job__in=administered_jobs)

        # exclude already taken shifts
        shifts = shifts.exclude(id__in=self.helper.shifts.all())

        # add field
        self.fields['shifts'] = forms.ModelMultipleChoiceField(
            widget=forms.CheckboxSelectMultiple,
            queryset=shifts, required=True) 
Example 29
Project: helfertool   Author: helfertool   File: helper.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.helper = kwargs.pop('helper')
        self.user = kwargs.pop('user')

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

        event = self.helper.event

        # field that contains all jobs if
        #  - user is admin for job
        #  - helper is not already coordinator for this job

        # all administered jobs
        coordinated_jobs = self.helper.coordinated_jobs
        jobs = [job.pk for job in event.job_set.all()
                if job.is_admin(self.user) and job not in coordinated_jobs]

        # we need a queryset
        jobs = Job.objects.filter(pk__in=jobs)

        # add field
        self.fields['jobs'] = forms.ModelMultipleChoiceField(
            widget=forms.CheckboxSelectMultiple,
            queryset=jobs, required=True) 
Example 30
Project: djongo   Author: nesdis   File: fields.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, name, model_form_class, model_form_kw, model_container,
                 admin=None, request=None, *args, **kwargs):
        form_fields = []
        mdl_form_field_names = []
        widgets = []
        model_form_kwargs = model_form_kw.copy()

        try:
            model_form_kwargs['prefix'] = model_form_kwargs['prefix'] + '-' + name
        except KeyError:
            model_form_kwargs['prefix'] = name

        initial = kwargs.pop('initial', None)
        if initial:
            model_form_kwargs['initial'] = initial

        self.model_form_class = _get_model_form_class(
            model_form_class, model_container, admin, request)
        self.model_form_kwargs = model_form_kwargs
        self.admin = admin
        self.request = request

        error_messages = {
            'incomplete': 'Enter all required fields.',
        }

        self.model_form = self.model_form_class(**model_form_kwargs)
        for field_name, field in self.model_form.fields.items():
            if isinstance(field, (forms.ModelChoiceField, forms.ModelMultipleChoiceField)):
                continue
            elif isinstance(field, ArrayFormField):
                field.name = '%s-%s' % (self.model_form.prefix, field_name)
            form_fields.append(field)
            mdl_form_field_names.append(field_name)
            widgets.append(field.widget)

        widget = EmbeddedFormWidget(mdl_form_field_names, widgets)
        super().__init__(error_messages=error_messages, fields=form_fields,
                         widget=widget, require_all_fields=False, *args, **kwargs)