Malcom is absolutely right, apologies for sending untested code to the
list.

--Derek

On Jan 20, 4:53 pm, Malcolm Tredinnick <malc...@pointy-stick.com>
wrote:
> On Tue, 2009-01-20 at 11:00 -0800, Derek Payton wrote:
> > The issue is that CLIENT_CHOICES is only evaluated once, when the
> > server is started an all the code is loaded into memory. Try wrapping
> > it all in a function, thusly:
>
> > def CLIENT_CHOICES()
> >     choices = [
> >         ('', 'Select Client'),
> >     ]
> >     clients = CustomerMaster.objects.all().order_by('customer_name')
> >     for client in clients:
> >         choices.extend([(client.id, client.customer_name)])
> >     return choices
>
> > class CreateForm(forms.Form):
> >         client = forms.ChoiceField(choices=CLIENT_CHOICES())
>
> > Now, every time the model is loaded, CLIENT_CHOICES() will be called
> > and you'll get fresh values.
>
> Everything correct, except that "every time" means "exactly once; when
> the module is imported". You haven't changed anything. The
> CLIENT_CHOICES() function is called when the form definition is parsed.
>
> (Also, the black helicopter briagde will be arriving at your house soon,
> to talk to you about not naming your function with all capital letters.
> Please take their advice to heart. We don't like having to send them
> around twice.)
>
> If somebody wants to initialise the choices afresh, each time a form
> instance is created, you have to do it in __init__. For example:
>
>         class CreateForm(forms.Form):
>            client = forms.ChoiceField(choices=())
>
>            def __init__(self, *args, **kwargs):
>               super(CreateForm, self).__init__(*args, **kwargs)
>               self.fields["client"].choices = CLIENT_CHOICES()
>
> The __init__ method on a class is only called when you create an
> *instance* of the class (not at import time) and it is called every such
> time. So this sets the "choices" attribute on the "client" field to a
> fresh value for each instance.
>
> Regards,
> Malcolm
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to