本文介绍了Django自动生成选择字段的选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单(forms.Form)自动生成自己的选择字段的选择:

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())

我的问题是,这显示为选择框(如意图),但其内容以某种方式进行缓存。在我重新启动本地PC上的dev服务器或远程服务器上的apache之前,新条目不会显示。

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和其他类型的缓存被关闭。

PS. memchached and other sorts of caching are turned off.

推荐答案

我认为你需要通过init来做到这一点,表单被调用,像

I think you need to do this via the init so it is evaluate when form is called, something like

例如

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

这篇关于Django自动生成选择字段的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 17:54