Ticket #12215: modelchoice_iterator_len.2.diff

File modelchoice_iterator_len.2.diff, 1.6 KB (added by Alex Gaynor, 15 years ago)
  • django/forms/models.py

    diff --git a/django/forms/models.py b/django/forms/models.py
    index 61ff8e4..40bc942 100644
    a b class ModelChoiceIterator(object):  
    910910            for obj in self.queryset.all():
    911911                yield self.choice(obj)
    912912
     913    def __len__(self):
     914        return len(self.queryset)
     915
    913916    def choice(self, obj):
    914917        if self.field.to_field_name:
    915918            key = obj.serializable_value(self.field.to_field_name)
    916919        else:
    917920            key = obj.pk
    918921        return (key, self.field.label_from_instance(obj))
     922   
    919923
    920924
    921925class ModelChoiceField(ChoiceField):
  • tests/regressiontests/model_forms_regress/tests.py

    diff --git a/tests/regressiontests/model_forms_regress/tests.py b/tests/regressiontests/model_forms_regress/tests.py
    index 85e284b..4c23b81 100644
    a b class CustomFieldSaveTests(TestCase):  
    100100        # It's enough that the form saves without error -- the custom save routine will
    101101        # generate an AssertionError if it is called more than once during save.
    102102        form = CFFForm(data = {'f': None})
    103         form.save()
    104  No newline at end of file
     103        form.save()
     104
     105
     106class ModelChoiceIteratorTests(TestCase):
     107    def test_len(self):
     108        class Form(forms.ModelForm):
     109            class Meta:
     110                model = Article
     111                fields = ["publications"]
     112       
     113        Publication.objects.create(title="Pravda",
     114            date_published=date(1991, 8, 22))
     115        f = Form()
     116        self.assertEqual(len(f.fields["publications"].choices), 1)
Back to Top