<p>我找到了一个办法让它工作。说实话,我不太了解这里发生的每一个方面,但我从相关的问题上把它弄得一头雾水。你知道吗</p>
<p>解决方法似乎是创建一个显式的modelform并使用ChoiceField的延迟版本。我找到了后者的代码<a href="https://gist.github.com/lsbardel/232372" rel="nofollow noreferrer">here</a>。这是我的表单.py地址:</p>
<pre><code>class LazyChoiceField(ChoiceField):
'''
A Lazy ChoiceField.
This ChoiceField does not unwind choices until a deepcopy is called on it.
This allows for dynamic choices generation every time an instance of a Form is created.
'''
def __init__(self, *args, **kwargs):
# remove choices from kwargs.
# choices should be an iterable
self._lazy_choices = kwargs.pop('choices',())
super(LazyChoiceField,self).__init__(*args, **kwargs)
def __deepcopy__(self, memo):
result = super(LazyChoiceField,self).__deepcopy__(memo)
lz = self._lazy_choices
if callable(lz):
lz = lz()
result.choices = lz
return result
class IssueForm(forms.ModelForm):
who_can_help = LazyChoiceField(choices=((PEOPLE, _('People')),
(OWNERS, _('Owners')),
(EXPERIENCED_PEOPLE, _('People with experience'))))
class Meta:
model = Issue
fields = ['title', 'description', 'plan']
</code></pre>
<p>我是从<a href="https://github.com/SmileyChris/django-countries/issues/135" rel="nofollow noreferrer">this similar issue</a>那里得到这个主意的。你知道吗</p>
<p>并不是说我不知道为什么这样做,但在我的脑海里它还没有那么清晰,所以如果有人对为什么需要这样做以及为什么这样做有任何进一步的见解,他们仍然是受欢迎的。你知道吗</p>