4

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

表格.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()

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

4

2 回答 2

6
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()]
于 2013-03-13T20:18:29.670 回答
3

Domain每次实例化 a 时都需要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)
    ...
于 2013-03-13T20:15:30.963 回答