コード例 #1
0
 def test_queryset_manager(self):
     f = forms.ModelChoiceField(Category.objects)
     self.assertEqual(len(f.choices), 4)
     self.assertEqual(list(f.choices), [
         ('', '---------'),
         (self.c1.pk, 'Entertainment'),
         (self.c2.pk, 'A test'),
         (self.c3.pk, 'Third'),
     ])
コード例 #2
0
    def test_overridable_choice_iterator(self):
        """
        Iterator defaults to ModelChoiceIterator and can be overridden with
        the iterator attribute on a ModelChoiceField subclass.
        """
        field = forms.ModelChoiceField(Category.objects.all())
        self.assertIsInstance(field.choices, ModelChoiceIterator)

        class CustomModelChoiceIterator(ModelChoiceIterator):
            pass

        class CustomModelChoiceField(forms.ModelChoiceField):
            iterator = CustomModelChoiceIterator

        field = CustomModelChoiceField(Category.objects.all())
        self.assertIsInstance(field.choices, CustomModelChoiceIterator)
コード例 #3
0
 def test_choices_freshness(self):
     f = forms.ModelChoiceField(Category.objects.all())
     self.assertEqual(len(f.choices), 4)
     self.assertEqual(list(f.choices), [
         ('', '---------'),
         (self.c1.pk, 'Entertainment'),
         (self.c2.pk, 'A test'),
         (self.c3.pk, 'Third'),
     ])
     c4 = Category.objects.create(name='Fourth', slug='4th', url='4th')
     self.assertEqual(len(f.choices), 5)
     self.assertEqual(list(f.choices), [
         ('', '---------'),
         (self.c1.pk, 'Entertainment'),
         (self.c2.pk, 'A test'),
         (self.c3.pk, 'Third'),
         (c4.pk, 'Fourth'),
     ])
コード例 #4
0
    def test_choices(self):
        f = forms.ModelChoiceField(Category.objects.filter(pk=self.c1.id), required=False)
        self.assertIsNone(f.clean(''))
        self.assertEqual(f.clean(str(self.c1.id)).name, 'Entertainment')
        with self.assertRaises(ValidationError):
            f.clean('100')

        # len() can be called on choices.
        self.assertEqual(len(f.choices), 2)

        # 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, 'A test'),
        ])
        self.assertEqual(f.clean(self.c2.id).name, 'A test')
        with self.assertRaises(ValidationError):
            f.clean(self.c3.id)

        # Choices can be iterated repeatedly.
        gen_one = list(f.choices)
        gen_two = f.choices
        self.assertEqual(gen_one[2], (self.c2.pk, 'A test'))
        self.assertEqual(list(gen_two), [
            ('', '---------'),
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, 'A test'),
        ])

        # Overriding label_from_instance() to print custom labels.
        f.queryset = Category.objects.all()
        f.label_from_instance = lambda obj: 'category ' + str(obj)
        self.assertEqual(list(f.choices), [
            ('', '---------'),
            (self.c1.pk, 'category Entertainment'),
            (self.c2.pk, 'category A test'),
            (self.c3.pk, 'category Third'),
        ])
コード例 #5
0
    def test_basics(self):
        f = forms.ModelChoiceField(Category.objects.all())
        self.assertEqual(list(f.choices), [
            ('', '---------'),
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, 'A test'),
            (self.c3.pk, 'Third'),
        ])
        with self.assertRaises(ValidationError):
            f.clean('')
        with self.assertRaises(ValidationError):
            f.clean(None)
        with self.assertRaises(ValidationError):
            f.clean(0)

        # Invalid types that require TypeError to be caught.
        with self.assertRaises(ValidationError):
            f.clean([['fail']])
        with self.assertRaises(ValidationError):
            f.clean([{'foo': 'bar'}])

        self.assertEqual(f.clean(self.c2.id).name, 'A test')
        self.assertEqual(f.clean(self.c3.id).name, 'Third')

        # Add a Category object *after* the ModelChoiceField has already been
        # instantiated. This proves clean() checks the database during clean()
        # rather than caching it at  instantiation time.
        c4 = Category.objects.create(name='Fourth', url='4th')
        self.assertEqual(f.clean(c4.id).name, 'Fourth')

        # Delete a Category object *after* the ModelChoiceField has already been
        # instantiated. This proves clean() checks the database during clean()
        # rather than caching it at instantiation time.
        Category.objects.get(url='4th').delete()
        msg = "['Select a valid choice. That choice is not one of the available choices.']"
        with self.assertRaisesMessage(ValidationError, msg):
            f.clean(c4.id)
コード例 #6
0
 class CategoriesForm(forms.Form):
     radio = forms.ModelChoiceField(queryset=categories, widget=forms.RadioSelect)
     checkbox = forms.ModelMultipleChoiceField(queryset=categories, widget=forms.CheckboxSelectMultiple)
コード例 #7
0
 def test_choices_not_fetched_when_not_rendering(self):
     with self.assertNumQueries(1):
         field = forms.ModelChoiceField(Category.objects.order_by('-name'))
         self.assertEqual('Entertainment', field.clean(self.c1.pk).name)
コード例 #8
0
 def test_disabled_modelchoicefield_has_changed(self):
     field = forms.ModelChoiceField(Author.objects.all(), disabled=True)
     self.assertIs(field.has_changed('x', 'y'), False)
コード例 #9
0
        class ModelChoiceForm(forms.ModelForm):
            author = forms.ModelChoiceField(Author.objects.all(), disabled=True)

            class Meta:
                model = Book
                fields = ['author']
コード例 #10
0
 class ModelChoiceForm(forms.Form):
     category = forms.ModelChoiceField(Category.objects.all(), widget=forms.RadioSelect)
コード例 #11
0
        class ModelChoiceForm(forms.Form):
            category = forms.ModelChoiceField(queryset=None)

            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.fields['category'].queryset = Category.objects.filter(slug__contains='test')
コード例 #12
0
 class ModelChoiceForm(forms.Form):
     category = forms.ModelChoiceField(Category.objects.all())
コード例 #13
0
 def test_choices_bool_empty_label(self):
     f = forms.ModelChoiceField(Category.objects.all(), empty_label='--------')
     Category.objects.all().delete()
     self.assertIs(bool(f.choices), True)