Django Forms:如何重新评估每个实例的默认变量

时间:2013-12-28 21:08:10

标签: python django django-forms

我有一个Django表单(作为django.forms.Form的子类),它有一个ChoiceField(即<select>下拉列表)。 ChoiceField的默认选项列表由数据库记录组成,因此它会定期更改。现在,列表仅在我重新启动服务器时更新。如何定义类,以便每个新实例重新评估选择?

编辑:抱歉,我应该从头开始添加。以下是代码示例:

class MonthInitializationForm(forms.Form):
    now = datetime.datetime.now()

    # list containing datetime.date objects of the current month, and the following 11 months
    months = [utilities.add_months(now, i) for i in range(0, 13)]

    # generate list of choices in form ('12/2014', 'December 2014') from months list
    choices = []

    for month in months:

        # if this form hasn't already been submitted for this month
        if not utilities.is_initialized(date=month):
            choices.append((month.strftime('%m/%Y'), month.strftime('%B %Y')))

    month = forms.ChoiceField(choices=months_choices)

基本上,这种形式“初始化”一个月。我只希望在接下来的0-11个月内有几个尚未初始化的月份显示为选项。由于这不是一个真正的SQL查询,我无法使用queryset来定义,我可以吗?那么,我如何使用forms.ChoiceField或forms.ModelChoiceField来使这个工作,以便用每个实例重新评估选择?

2 个答案:

答案 0 :(得分:1)

您必须使用表单的__init__功能来执行所需操作。从db生成选项列表并将其分配给该字段。像这样:

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    list_of_choices = (
                    (obj.some_field1, obj.some_field2) for obj in SomeTable.objects.all()
                    )
    self.fields['field_name'].choices = list_of_choices

答案 1 :(得分:0)

对于从模型或查询集动态生成的选择字段,您应该使用专为此用例设计的ModelChoiceField,并在表单即时时自动刷新其选择列表。