从动态 ModelForm 中删除字段
在 ModelForm 中,我必须测试用户权限,让他们填写正确的字段:
它的定义如下:
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 是模型中定义的每个字段都会显示在模板上。
如果不需要,我想从表单中删除它们:
示例:如果用户对模型公司没有权限,则不会在模板的渲染表单中使用它。
问题是您必须将字段列表放在具有字段或排除属性的表单元类,但我不知道如何动态管理它们。
有什么想法吗??
预先感谢您的任何答复。
In a ModelForm, i have to test user permissions to let them filling the right fields :
It is defined like this:
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
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需从 self.fields 字典中删除它:
Just delete it from the self.fields dict: