On Thu, May 12, 2011 at 10:09 AM, Jani Tiainen <rede...@gmail.com> wrote: > On Thu, 2011-05-12 at 09:59 +0200, Thomas Weholt wrote: >> I got a model looking something like this >> >> class SomeModel(models.Model): >> somefield = models.CharField(max_length=100, choices=somemethod()) >> >> The problem is that somemethod, which produces the choices to give in >> the form in the admin, is called when the module is imported, not when >> the form instance is created. The result from the somemethod call is >> dynamic based on custom user defined code and not some static tuple or >> list. >> >> So my question is: how can I get the choices to be set at the time of >> form creation? Tried overriding the __init__, but then somefield was >> only available as a string and I could not set any choice-property. > > You hit common "problem". You do assignment of function/method call > result not the callable itself. Small but significant difference. > > So whenever somefield = models.Charfield(choices=somemethod()) is > evaluated it uses result of method call. And due the way objects are > called value is put there when class itself is constructed (imported). > This is just how it works with Python. > > To be able to do dynamic chocies (which also is documented that > something might be wrong if choices are dynamic)) you have to pass > callable - which in python means that leave out parenthesis: > > somefield = models.CharField(choices=somemethod)
Ah crap!! Of course. Thanks alot Jani :-) Thomas -- 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.