基本思想是能够基于模型权限检查(使用基于类的通用视图)隐藏一些表单字段。很明显,我可以覆盖视图get
并post
检查表单权限并构造表单,但是没有更简洁的方法来实现这一点吗?
到目前为止,视图和形式都非常简单
class UserProfileUpdateView(UpdateView):
model = UserProfile
template_name = "profile/update.html"
form_class = UserProfileForm
class UserProfileForm(forms.ModelForm):
def __init__(self, can_change_position=False, can_change_manager=False, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
self._process_permission('position', can_change_position)
self._process_permission('manager', can_change_manager)
def _process_permission(self, field, permitted):
if permitted:
self.fields.append(field)
class Meta:
model = UserProfile
fields = ['field1', 'field2', 'field3', ...]
我是否遗漏了一些明显的东西,或者只是按照错误的方式?
更新看起来我的意图并不明确。我发布的代码中有一个错误,所以到目前为止给出的答案是如何修复错误。我已经修复了它,但问题不在于如何在运行时在表单上添加/删除字段(很明显)。问题是,是否有任何方法可以使用基于类的通用视图基于request
值(例如)添加/删除字段。request.user
因此,再一次,直接的方法是重载get
并post
在视图上执行检查并实例化表单。但它在某种程度上重复了现有的 django 行为(即管理视图传递request
给get_form
)。那么,没有更清洁的方法来实现它吗?