如何修改管理页面上的选择 - django [英] how to modify choices on admin pages - django

查看:22
本文介绍了如何修改管理页面上的选择 - django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,它有一个名为state"的字段:

I have a model that has a field named "state":

class Foo(models.Model):
    ...
    state = models.IntegerField(choices = 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?

推荐答案

您需要在 ModelAdmin 类中为该模型使用自定义 ModelForm.在自定义 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆