django - 表单字段不会在没有服务器重置的情况下更新...再次实例化一个类

时间:2013-03-13 20:12:16

标签: python django

我有一个从模型中收集数据的表单。问题是如果我更新模型/数据库中的信息,它将不会在表单中显示,直到服务器重新启动。

forms.py

class RecordForm(forms.Form):
  name = forms.CharField(max_length=255)
  type_choices = []
  choices = Domain.objects.all()
  for choice in choices:
    type_choices.append( (choice.id, choice.name) )
  domain = forms.TypedChoiceField(choices=type_choices)
  type = forms.TypedChoiceField(choices=Record.type_choices)
  content = forms.CharField()
  ttl = forms.CharField()
  comment = forms.CharField()

我从Domain模型中提取数据。在网站上我有一个页面输入域信息。然后是另一个页面,它将在下拉框中列出这些域。但是,如果添加或删除任何内容,则在重新启动服务器之前,它不会显示在保管箱中。我的猜测是django只调用一次表单类。有没有办法确保在创建变量时重新运行类代码?

2 个答案:

答案 0 :(得分:4)

class RecordForm(forms.Form):
    name = forms.CharField(max_length=255)
    domain = forms.TypedChoiceField(choices=[])
    type = forms.TypedChoiceField(choices=...)
    content = forms.CharField()
    ttl = forms.CharField()
    comment = forms.CharField()

    def __init__(self, *args, **kwargs):
        super(RecordForm, self).__init__(*args, **kwargs)
        self.fields['type'].choices = [(c.id, c.name) for c in Domain.objects.all()]

答案 1 :(得分:3)

每次实例化Domain时,您需要通过覆盖模型表单的RecordForm来获取__init__个对象。

class RecordForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(RecordForm, self).__init__(*args, **kwargs)
        self.type_choices = [(choice.id, choice.name,) for choice in \
            Domain.objects.all()]

    domain = forms.TypedChoiceField(choices=self.type_choices)
    ...