【问题标题】:Django forms choicefield automatically generated choicesDjango 表单选择域自动生成的选择
【发布时间】:2011-08-24 03:31:56
【问题描述】:

我有一个表单(forms.Form),它会自动为自己的选择域生成选项:

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 上的开发服务器或远程服务器上的 apache 之前,新条目不会显示。

何时评估那段代码?我怎样才能让它重新计算条目每次

附言。 memchached 和其他类型的缓存已关闭。

【问题讨论】:

    标签: django forms choicefield


    【解决方案1】:

    从 1.8 版开始提供更好的解决方案:Django 的 ChoiceField 有 ability to pass a callable to choices

    使用 2 元组的可迭代(例如,列表或元组)作为 此字段的选择,或返回此类迭代的可调用对象。 如果参数是可调用的,则对每个参数进行评估 初始化字段表单的时间。

    所以现在你可以写了

    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)
    

    您也可以使用ModelChoiceField 完成此任务。

    【讨论】:

      【解决方案2】:

      我认为您需要通过 init 执行此操作,以便在调用表单时进行评估,例如

      例如

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-29
        • 2011-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多