1👍
✅
There are different possibilities to check the permissions, though they all require you writing the permission checking code yourself. There might be some django packages providing the functionality for you, but I don’t know any.
You could create one permissions for each field that you would like to permit / deny in the model’s META.permissions
attribute and then check the permissions per user.
The checks can be done in different places. Either in your view directly, in the model’s save
method or in the form’s clean_<field_name>
method. I would prefer the clean_<field_name>
method. e.g.:
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
For this solution, you would need to pass the request.user
to the form on instantiation.
👤Tim
Source:stackexchange.com