我正在做一个项目,需要一些用户访问(查看)模型的字段,但他们无法更新字段。有没有办法做到这一点? 这不会在管理站点中使用。
另外,我想根据模型的字段值提供权限。有没有办法做到这一点?
谢谢!
答案 0 :(得分:0)
检查权限有不同的可能性,但它们都要求您自己编写权限检查代码。可能有一些django软件包为您提供功能,但我不知道。
您可以为模型的save
属性中允许/拒绝的每个字段创建一个权限,然后检查每个用户的权限。
检查可以在不同的地方进行。您可以直接在视图中,在模型的clean_<field_name>
方法中,也可以在表单的clean_<field_name>
方法中使用。我更喜欢class MyForm(forms.ModelForm):
class Meta:
model = <YOUR MODEL>
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(MyForm, self).__init__(*args, **kwargs)
def clean_myfield(self):
cd = self.cleaned_data
# check if the user has the required permission to change the field
if self.user.has_perm(<YOUR PERMISSION>):
return cd.get('myfield')
# if not, return the original value
if self.instance:
return self.instance.myfield
# If it can happen that there is no instance yet,
# you should return a sensible default here
return None
方法。 e.g:
request.user
对于此解决方案,您需要在实例化时将<button id="main" onclick=doThis()>Main</button>
<div id="result">h<div>
传递给表单。