If I have models like this..
class Family(Model):
name = models.CharField()
class Father(Model):
family = ForeignKey(Family)
class Mother(Model):
family = ForeignKey(Family)
class Child(Model):
family = ForeignKey(Family)
Django makes group permissions automatically so I can define groups that can edit/create/etc... the family model.
How can I limit it to only let a user edit a certain instance of the family model? So if I want the 'Johnson' family admin to only have permission to edit things under the 'Johnson' family tree.
I can think of two ways, one would be defining a custom permission like (https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#custom-permissions) but I have no idea what the docs are saying there and they do not do a good job of explaining it.
I can also think of possibly adding a field on the user model and checking the value of that, but it feels wrong to do it that way...
I can imagine two ways for achieving what you want, but that'd be experimental and I don't know if it would follow the good practices :
With codename partially based on the instance. For example, creating a permission with a codename containing the instance the user could edit :
perm = Permission.objects.create(codename='can_create_'+str(obj.id),
name='can edit instance with id ' + str(obj.id))
user.user_permissions.add(perm)
and then :
if user.has_perm('can_create_' + str(relevant_id)):
Probably the field idea you had yourself :
class myModel(models.Model):
editors = models.ManyToManyField(User, related_name='mymodel_can_edit')
and then just add and remove the instances a user can delete in its mymodel_can_edit field just like you manage the permissions in its user_permissions field.
But I didn't test any of these solution. If you try it could you tell what you think about it? :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With