本文介绍了如何修改管理页面上的选择 - django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为state的模型:
I have a model that has a field named "state":
class Foo(models.Model):
...
state = models.IntegerField(choices = STATES)
...
对于每个状态,可能的选择是所有STATES的某个子集。例如:
For every state, possible choices are a certain subset of all STATES. For example:
if foo.state == STATES.OPEN: #if foo is open, possible states are CLOSED, CANCELED
...
if foo.state == STATES.PENDING: #if foo is pending, possible states are OPEN,CANCELED
...
因此,当foo.state变为新状态时,其可能的选择集也会更改。
As a result, when foo.state changes to a new state, its set of possible choices changes also.
如何在管理员添加/更改页面上实现此功能?
How can I implement this functionality on Admin add/change pages?
推荐答案
您需要对于那个模型在自定义ModelForm的__init__方法中,您可以动态设置该字段的选项:
You need to use a custom ModelForm in the ModelAdmin class for that model. In the custom ModelForm's __init__ method, you can dynamically set the choices for that field:
class FooForm(forms.ModelForm):
class Meta:
model = Foo
def __init__(self, *args, **kwargs):
super(FooForm, self).__init__(*args, **kwargs)
current_state = self.instance.state
...construct available_choices based on current state...
self.fields['state'].choices = available_choices
您可以这样使用:
class FooAdmin(admin.ModelAdmin):
form = FooForm
这篇关于如何修改管理页面上的选择 - django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!