ModelForm.Meta中的条件字段 [英] Conditional fields in a ModelForm.Meta

查看:54
本文介绍了ModelForm.Meta中的条件字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们在Django应用程序中有一个自定义用户模型.为了使其在管理页面上可CRUD,我们想定义一些表格.

Assume we have a custom user model in a Django application. In order to make it CRUDable from the admin page, we want to define some forms.

下面是 UserChangeForm ,用于修改我们的自定义用户模型的实例

Below is the UserChangeForm used to modify an instance of our custom user model

class UserChangeForm(forms.ModelForm):

    class Meta:
        model  = MyCustomUser
        fields = (
            ...,
            'email',
            'is_active',
            'is_admin',
            'groups',
            ....
        )

问题是:如何基于模型实例在 Meta 类中实现条件 字段超出了Meta的范围)?

The question is: how do I implement a conditional fields in the Meta class based on the model instance (i.e., out of scope for Meta)?

目标是声明类似的内容

def get_fields(self):
    if self.instance.is_company:
        return ('email', 'company_name', 'headquarters')
    else:
       return ('email', 'first_name', 'last_name')

在外部类中,然后找到一种方法将函数的结果注入到 Meta.fields 中.有什么主意吗?

in the outer class, then find a way to inject the result of the function in Meta.fields. Any idea?

推荐答案

您可以在 __ init __()构造函数中从表单中删除字段:

You can delete fields from the form in the __init__() constructor:

class UserChangeForm(forms.ModelForm):

    class Meta:
        fields = ('email', 'company_name', 'headquarters',
                           'first_name', 'last_name', )

    def __init__(self, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)
        if self.instance.is_company:
            fields_to_delete = ('first_name', 'last_name')
        else:
            fields_to_delete = ('company_name', 'headquarters')
        for field in fields_to_delete:
            del self.fields[field]

这篇关于ModelForm.Meta中的条件字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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