Django forms choicefield automatically generated choices

拟墨画扇 提交于 2019-12-21 22:55:05

问题


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 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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/5978884/django-forms-choicefield-automatically-generated-choices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!