从动态的ModelForm中删除一个字段 [英] Removing a fields from a dynamic ModelForm

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

问题描述

在ModelForm中,我必须测试用户权限,让他们填写正确的字段:

In a ModelForm, i have to test user permissions to let them filling the right fields :

它的定义如下:

class TitleForm(ModelForm):    
    def __init__(self, user, *args, **kwargs):
        super(TitleForm,self).__init__(*args, **kwargs)            
        choices = ['','----------------']
        # company
        if user.has_perm("myapp.perm_company"): 
            self.fields['company'] = forms.ModelChoiceField(widget=forms.HiddenInput(),
                queryset=Company.objects.all(), required=False) 
            choices.append(1,'Company')
        # association
        if user.has_perm("myapp.perm_association")
            self.fields['association'] =
            forms.ModelChoiceField(widget=forms.HiddenInput(),
                queryset=Association.objects.all(), required=False)
            choices.append(2,'Association')
        # choices
        self.fields['type_resource'] = forms.ChoiceField(choices = choices)

    class Meta:
        Model = Title  

这个ModelForm做的工作:我隐藏模板上的每个字段,并使它们出现感谢javascript ...

问题是这个ModelForm是模型中定义的每个字段都将显示在模板上。

如果不需要,我想从表单中删除它们:

例如:如果用户对模型公司没有权利,则不会以模板中呈现的形式使用它。

This ModelForm does the work : i hide each field on the template and make them appearing thanks to javascript...
The problem is this ModelForm is that each field defined in the model will be displayed on the template.
I would like to remove them from the form if they are not needed:
exemple : if the user has no right on the model Company, it won't be used it in the rendered form in the template.

问题是你必须将表单的Meta类中的列表放在字段排除属性中,但是我不知道如何动态地管理它们

The problem of that is you have to put the list of fields in the Meta class of the form with fields or exclude attribute, but i don't know how to manage them dynamically.

任何想法?

感谢您的任何答案。

Any Idea??
Thanks by advance for any answer.

推荐答案

只需删除它来自 self.fields dict:

Just delete it from the self.fields dict:

if not user.has_perm("blablabla"):
    del self.fields["company"]

这篇关于从动态的ModelForm中删除一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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