potential bug

24 views
Skip to first unread message

Mark Nesterovych

unread,
Jun 14, 2015, 10:27:40 AM6/14/15
to django...@googlegroups.com
Hello.
I've just finished small django site, and keep going on creating tests.
I've found and issue with Model.objects.values_list  method.
Looks like it disregard test database and looks into production one.

Some details.
I have a form with a filed customer = forms.ChoiseField(choises=Customer.objects.values_list('id', 'name'))

When this form initing during tests, it loads data from production database.

My test looks like this.
class CustomerFormTest(TestCase):
    def setUp:
         self.customer = Customer.objects.create(name='test name')

    def test_form_creation(self):
        form = CustomerLoginForm()
        self.assertIn('test name', form.as_ul())


Assertion fails, and when I printing form content, I see select widget with options from production database objects.

Can somebody confirm it's a bug ?
Thank you.




Tom Evans

unread,
Jun 14, 2015, 3:37:26 PM6/14/15
to django...@googlegroups.com
It's not a bug. You are specifying the choices when the form is
defined, and at that point there is nothing in the database and so the
form has no choices. Since the field is never redefined in the form,
the choices will be whatever existed in the database when the form is
defined, which is a bad way of designing the form.

Typically, when your choices are instances of a model, you would not
use ChoiceField, but ModelChoicefield. ModelChoiceField takes a
queryset when defining the form, and avoids evaluating the queryset
until the form is instantiated, which avoids the issue. The
documentation also explains how you can specify the queryset more
dynamically if that is required.

https://docs.djangoproject.com/en/1.8/ref/forms/fields/#modelchoicefield

(I'm assuming that the typo "choises" is only present in your email,
and your code correctly says "choices" and "ChoiceField")

Cheers

Tom

Mark Nesterovych

unread,
Jun 15, 2015, 5:27:08 AM6/15/15
to django...@googlegroups.com
Forgot about ModelChoise.
Thank you.
Reply all
Reply to author
Forward
0 new messages