gpt4 book ai didi

Django 表单choicefield 自动生成选择

转载 作者:行者123 更新时间:2023-12-03 22:56:28 25 4
gpt4 key购买 nike

我有一个表单 (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 和其他类型的缓存已关闭。

最佳答案

从 1.8 版开始提供更好的解决方案:Django 的 ChoiceField 有 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.



所以现在你可以写
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对于这个任务。

关于Django 表单choicefield 自动生成选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5978884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com