Django forms choicefield automatically generated choices
I have a form (forms.Form) that automatically generates the choices for its own choicefield as such:
class UserForm(forms.Form):
def generate_choices():
from vn.account.models import UserProfile
up = UserProfile.objects.filter(user__isnull=True)
choices = [('0','--')]
choices += ([(s.id ,'%s %s (%s), username: %s, email: %s' % (s.first_name, s.last_name, s.company_name, s.username, s.email)) for s in up])
return choices
user = forms.ChoiceField(label=_('Select from interest form'), choices=generate_choices())
My problem is that this shows up as a select box (as intented) but its contents are开发者_StackOverflow中文版 cached somehow. New entries do not show up before i restart the dev server on my local pc, or apache on the remote server.
When is that piece of code evaluated? How can i make it so that it re-calculates the entries every time ?
PS. memchached and other sorts of caching are turned off.
A better solution is available starting from version 1.8: Django's ChoiceField has ability to pass a callable to choices.
Either an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field, or a callable that returns such an iterable. If the argument is a callable, it is evaluated each time the field’s form is initialized.
So now you can just write
class UserForm(forms.Form):
def generate_choices():
from vn.account.models import UserProfile
up = UserProfile.objects.filter(user__isnull=True)
choices = [('0','--')]
choices += ([(s.id ,'%s %s (%s), username: %s, email: %s' % (s.first_name, s.last_name, s.company_name, s.username, s.email)) for s in up])
return choices
user = forms.ChoiceField(label=_('Select from interest form'), choices=generate_choices)
Also you can use ModelChoiceField for this task.
I think you need to do this via the init so it is evaluate when form is called, something like
e.g.
def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
from vn.account.models import UserProfile
up = UserProfile.objects.filter(user__isnull=True)
choices = [('0','--')]
choices += ([(s.id ,'%s %s (%s), username: %s, email: %s' % (s.first_name, s.last_name,s.company_name, s.username, s.email)) for s in up])
self.fields['user'].choices = choices
精彩评论