On Wed, 2007-05-23 at 06:01 -0700, [EMAIL PROTECTED] wrote:
> Hello,
> 
> I wrote a newforms form, but I have some problems when I want to test
> the class.  Here's the definition:
> 
> def _users():
>     print "calling _users()"
>     return [(u.id, u.get_full_name()) for u in
> User.objects.filter(is_active=True)]
> 
> class MemoForm(forms.Form):
>     body = forms.CharField(widget=forms.Textarea, required=True)
>     recipients = forms.MultipleChoiceField(choices=_users(),
> required=True)
> 
> This works fine, however when I run my tests, _users() is called at
> the very beginning, 

The reason this is happening is because the "recipients" line of code,
including the function call to _users() is executed at *import* time, so
very early in the game.

You could replace choices=_users() with "choices=_users" and change the
_users() function to be an iterable. That will mean it is evaluated the
first time you need the choices (so, as late as possible). It will only
be evaluated once, though, so you can't use this to make the choices act
like a ForeignKey (updated every time you use it).

See
http://www.pointy-stick.com/blog/2007/03/26/django-tips-variable-choice-lists/ 
for a reasonably detailed example.

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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to