预填充1个外键的表单字段

时间:2016-01-07 13:58:00

标签: python django

以前我让用户从颜色下拉中选择,但我想为它们选择一个,所以我使用以下代码来确定哪些颜色是有效选择然后随机选择一个。我试图让它在表单中预先填充,我收到了名称错误。我疯狂地挠头,因为我已经通过简单地将choice传递到模板来测试此代码。所以我知道代码在该上下文中正常运行。我可以不做我在下面做过的事情吗?

我启动服务器时遇到的错误是Name Error: name 'cur_colors' [at the list comprehension line] is not defined,但显然是......

class LimitedJobForm(forms.ModelForm):
    jobnum = forms.CharField(label='Job Number')
    #get colorchoice
    cur_jobs = Job.objects.filter(enddate__gte=(datetime.date.today()-timedelta(days=7)))
    all_colors = Color.objects.all()
    cur_colors = []
    for i in cur_jobs:
        cur_colors.append(i.color)
    aval_colors = [x for x in all_colors if x not in cur_colors]
    choice = random.choice(aval_colors)
    color = forms.CharField(initial=choice)

1 个答案:

答案 0 :(得分:1)

您还没有为此代码定义一个init方法,因此它只是单独读取每一行作为声明

将您的代码移动到init方法中,它应该可以正常工作!

class LimitedJobForm(forms.ModelForm):

    jobnum = forms.CharField(label='Job Number')
    color = forms.CharField()

    def __init__(self, *args, **kwargs):
        super(LimitedJobForm, self).__init__(*args, **kwargs)
        cur_jobs = Job.objects.filter(enddate__gte=(datetime.date.today()-timedelta(days=7)))
        all_colors = Color.objects.all()
        cur_colors = []
        for i in cur_jobs:
            cur_colors.append(i.color)
        aval_colors = [x for x in all_colors if x not in cur_colors]
        choice = random.choice(aval_colors)
        self.fields['color'].initial = choice