Forgot about ModelChoise.
Thank you.

On Sunday, 14 June 2015 22:37:26 UTC+3, Tom Evans wrote:
>
> On Sun, Jun 14, 2015 at 3:24 PM, Mark Nesterovych 
> <[email protected] <javascript:>> wrote: 
> > 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. 
>
> 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 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/64b6f961-3ad5-4b06-ac35-a5590c9c1de5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to