Python django.forms.ModelMultipleChoiceField() Examples
The following are 30
code examples of django.forms.ModelMultipleChoiceField().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.forms
, or try the search function
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: forms.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 8 votes |
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
Source File: forms.py From Spirit with MIT License | 7 votes |
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 #3
Source File: test_modelchoicefield.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
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 #4
Source File: test_modelchoicefield.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
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 #5
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
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 #6
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
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 #7
Source File: forms.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #8
Source File: forms.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #9
Source File: forms.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #10
Source File: forms.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #11
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
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 #12
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_model_multiple_choice_field_22745(self): """ #22745 -- Make sure that ModelMultipleChoiceField with CheckboxSelectMultiple widget doesn't produce unnecessary db queries when accessing its BoundField's attrs. """ class ModelMultipleChoiceForm(forms.Form): categories = forms.ModelMultipleChoiceField(Category.objects.all(), widget=forms.CheckboxSelectMultiple) form = ModelMultipleChoiceForm() field = form['categories'] # BoundField template = Template('{{ field.name }}{{ field }}{{ field.help_text }}') with self.assertNumQueries(1): template.render(Context({'field': field}))
Example #13
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_model_multiple_choice_number_of_queries(self): """ ModelMultipleChoiceField does O(1) queries instead of O(n) (#10156). """ persons = [Writer.objects.create(name="Person %s" % i) for i in range(30)] f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all()) self.assertNumQueries(1, f.clean, [p.pk for p in persons[1:11:2]])
Example #14
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_show_hidden_initial_changed_queries_efficiently(self): class WriterForm(forms.Form): persons = forms.ModelMultipleChoiceField( show_hidden_initial=True, queryset=Writer.objects.all()) writers = (Writer.objects.create(name=str(x)) for x in range(0, 50)) writer_pks = tuple(x.pk for x in writers) form = WriterForm(data={'initial-persons': writer_pks}) with self.assertNumQueries(1): self.assertTrue(form.has_changed())
Example #15
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_clean_does_deduplicate_values(self): class WriterForm(forms.Form): persons = forms.ModelMultipleChoiceField(queryset=Writer.objects.all()) person1 = Writer.objects.create(name="Person 1") form = WriterForm(data={}) queryset = form.fields['persons'].clean([str(person1.pk)] * 50) sql, params = queryset.query.sql_with_params() self.assertEqual(len(params), 1)
Example #16
Source File: forms.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #17
Source File: test_modelchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_disabled_modelmultiplechoicefield_has_changed(self): field = forms.ModelMultipleChoiceField(Author.objects.all(), disabled=True) self.assertIs(field.has_changed('x', 'y'), False)
Example #18
Source File: test_modelchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_choice_iterator_passes_model_to_widget(self): class CustomModelChoiceValue: def __init__(self, value, obj): self.value = value self.obj = obj def __str__(self): return str(self.value) class CustomModelChoiceIterator(ModelChoiceIterator): def choice(self, obj): value, label = super().choice(obj) return CustomModelChoiceValue(value, obj), label class CustomCheckboxSelectMultiple(CheckboxSelectMultiple): def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): option = super().create_option(name, value, label, selected, index, subindex=None, attrs=None) # Modify the HTML based on the object being rendered. c = value.obj option['attrs']['data-slug'] = c.slug return option class CustomModelMultipleChoiceField(forms.ModelMultipleChoiceField): iterator = CustomModelChoiceIterator widget = CustomCheckboxSelectMultiple field = CustomModelMultipleChoiceField(Category.objects.all()) self.assertHTMLEqual( field.widget.render('name', []), '''<ul> <li><label><input type="checkbox" name="name" value="%d" data-slug="entertainment">Entertainment</label></li> <li><label><input type="checkbox" name="name" value="%d" data-slug="test">A test</label></li> <li><label><input type="checkbox" name="name" value="%d" data-slug="third-test">Third</label></li> </ul>''' % (self.c1.pk, self.c2.pk, self.c3.pk), )
Example #19
Source File: test_modelchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_num_queries(self): """ Widgets that render multiple subwidgets shouldn't make more than one database query. """ categories = Category.objects.all() class CategoriesForm(forms.Form): radio = forms.ModelChoiceField(queryset=categories, widget=forms.RadioSelect) checkbox = forms.ModelMultipleChoiceField(queryset=categories, widget=forms.CheckboxSelectMultiple) template = Template( '{% for widget in form.checkbox %}{{ widget }}{% endfor %}' '{% for widget in form.radio %}{{ widget }}{% endfor %}' ) with self.assertNumQueries(2): template.render(Context({'form': CategoriesForm()}))
Example #20
Source File: test_uuid.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_model_multiple_choice_field_uuid_pk(self): f = forms.ModelMultipleChoiceField(UUIDPK.objects.all()) with self.assertRaisesMessage(ValidationError, "'invalid_uuid' is not a valid UUID."): f.clean(['invalid_uuid'])
Example #21
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_model_multiple_choice_required_false(self): f = forms.ModelMultipleChoiceField(Category.objects.all(), required=False) self.assertIsInstance(f.clean([]), EmptyQuerySet) self.assertIsInstance(f.clean(()), EmptyQuerySet) with self.assertRaises(ValidationError): f.clean(['0']) with self.assertRaises(ValidationError): f.clean([str(self.c3.id), '0']) with self.assertRaises(ValidationError): f.clean([str(self.c1.id), '0']) # queryset can be changed after the field is created. f.queryset = Category.objects.exclude(name='Third') self.assertEqual(list(f.choices), [ (self.c1.pk, 'Entertainment'), (self.c2.pk, "It's a test")]) self.assertQuerysetEqual(f.clean([self.c2.id]), ["It's a test"]) with self.assertRaises(ValidationError): f.clean([self.c3.id]) with self.assertRaises(ValidationError): f.clean([str(self.c2.id), str(self.c3.id)]) f.queryset = Category.objects.all() f.label_from_instance = lambda obj: "multicategory " + str(obj) self.assertEqual(list(f.choices), [ (self.c1.pk, 'multicategory Entertainment'), (self.c2.pk, "multicategory It's a test"), (self.c3.pk, 'multicategory Third')])
Example #22
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_model_multiple_choice_number_of_queries(self): """ ModelMultipleChoiceField does O(1) queries instead of O(n) (#10156). """ persons = [Writer.objects.create(name="Person %s" % i) for i in range(30)] f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all()) self.assertNumQueries(1, f.clean, [p.pk for p in persons[1:11:2]])
Example #23
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_model_multiple_choice_run_validators(self): """ ModelMultipleChoiceField run given validators (#14144). """ for i in range(30): Writer.objects.create(name="Person %s" % i) self._validator_run = False def my_validator(value): self._validator_run = True f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all(), validators=[my_validator]) f.clean([p.pk for p in Writer.objects.all()[8:9]]) self.assertTrue(self._validator_run)
Example #24
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
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 #25
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_model_multiple_choice_field_22745(self): """ #22745 -- Make sure that ModelMultipleChoiceField with CheckboxSelectMultiple widget doesn't produce unnecessary db queries when accessing its BoundField's attrs. """ class ModelMultipleChoiceForm(forms.Form): categories = forms.ModelMultipleChoiceField(Category.objects.all(), widget=forms.CheckboxSelectMultiple) form = ModelMultipleChoiceForm() field = form['categories'] # BoundField template = Template('{{ field.name }}{{ field }}{{ field.help_text }}') with self.assertNumQueries(1): template.render(Context({'field': field}))
Example #26
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_clean_does_deduplicate_values(self): class WriterForm(forms.Form): persons = forms.ModelMultipleChoiceField(queryset=Writer.objects.all()) person1 = Writer.objects.create(name="Person 1") form = WriterForm(data={}) queryset = form.fields['persons'].clean([str(person1.pk)] * 50) sql, params = queryset.query.sql_with_params() self.assertEqual(len(params), 1)
Example #27
Source File: test_modelchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_disabled_modelmultiplechoicefield_has_changed(self): field = forms.ModelMultipleChoiceField(Author.objects.all(), disabled=True) self.assertIs(field.has_changed('x', 'y'), False)
Example #28
Source File: test_modelchoicefield.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_num_queries(self): """ Widgets that render multiple subwidgets shouldn't make more than one database query. """ categories = Category.objects.all() class CategoriesForm(forms.Form): radio = forms.ModelChoiceField(queryset=categories, widget=forms.RadioSelect) checkbox = forms.ModelMultipleChoiceField(queryset=categories, widget=forms.CheckboxSelectMultiple) template = Template( '{% for widget in form.checkbox %}{{ widget }}{% endfor %}' '{% for widget in form.radio %}{{ widget }}{% endfor %}' ) with self.assertNumQueries(2): template.render(Context({'form': CategoriesForm()}))
Example #29
Source File: test_uuid.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_model_multiple_choice_field_uuid_pk(self): f = forms.ModelMultipleChoiceField(UUIDPK.objects.all()) with self.assertRaisesMessage(ValidationError, "'invalid_uuid' is not a valid UUID."): f.clean(['invalid_uuid'])
Example #30
Source File: related.py From python with Apache License 2.0 | 5 votes |
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)