Django ModelForm动态runTIme字段

时间:2018-03-31 16:11:41

标签: django django-models django-forms

如何在模型上动态添加未在Django 1.9.7上的runTime模型上定义的字段?

我知道我能做到:

  class ExampleForm(forms.ModelForm):
      class Meta:
          model = Example
          # if you don't define the list of fields __all__ won't get the dynamic one
          fields = '__all__'
      MY_CHOICES = (
          ('A', 'Choice A'),
          ('B', 'Choice B'),
      )
      stuff = forms.ChoiceField(choices=MY_CHOICES)

但是如果我需要在运行时收集的选项怎么办?例如:

  class ExampleForm(forms.ModelForm):
      class Meta:
          model = Example
          fields = '__all__'
      MY_CHOICES = (
          ('A', 'Choice A'),
          ('B', 'Choice B'),
      )
      def __init__(self, *args, **kwargs):
          super(ExampleForm, self).__init__(*args, **kwargs)
          self.stuff = forms.ChoiceField(choices=self.MY_CHOICES)
          # self.fields['stuff'] = forms.ChoiceField(choices=self.MY_CHOICES) Also does not work

返回错误

  

为示例指定的未知字段(填充)。

如何定义未在模型上定义的字段,并且需要从不同的查询中收集选择?

感谢。

修改:StackTrace

要重现错误,只需要求字段并在runTime添加字段,如下所示:

class ExampleForm(forms.ModelForm):
    class Meta:
        model = Example
        fields = '__all__'
    MY_CHOICES = (
        ('A', 'Choice A'),
        ('B', 'Choice B'),
    )
    def __init__(self, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)
        self.stuff = forms.ChoiceField(choices=self.MY_CHOICES)
        # self.fields['stuff'] = forms.ChoiceField(choices=self.MY_CHOICES) Also does not work

class ExampleAdmin(admin.ModelAdmin):
    fieldsets = (
        (None, {
            "fields": ("stuff",)
        }),
    )
    form = ExampleForm

1 个答案:

答案 0 :(得分:0)

对我来说,解决方案是稍后动态填充选项。

class ExampleForm(forms.ModelForm):
    class Meta:
        model = Example
        fields = '__all__'
    MY_CHOICES = (
        ('A', 'Choice A'),
        ('B', 'Choice B'),
    )
    stuff = forms.ChoiceField()
    def __init__(self, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)
        self.fields['stuff'].choices = self.MY_CHOICES

现在我的下一个目标是能够制作一个水平过滤器,其数据不是来自模型,而是来自其他外部来源。