django-rules icon indicating copy to clipboard operation
django-rules copied to clipboard

Type in predicates when called from template

Open kienerj opened this issue 4 years ago • 2 comments

I'm using django-rest-framework and in a template I want to limit what a user can do by showing or not showing according action (a button) based on users permissions. It's a detail view showing all the child records. A user can edit the child record, if the user is the creator or the creators supervisor. Hence in the predicates I compare current user to child record creator or supervisor. The predicates and rules work as expected.

The issue I'm facing is that when the permission is checked in the template and my predicates are called, the child record is passed in as OrderedDict and not as instance of it's model class. I suspect this is due to looping child instances in the template and the child instances are actually from a nested serializer? I'm speculating.

My current hack is to simply type-check inside the predicate.

Questions is, how can I solve this nicely? or what am I doing wrong?

kienerj avatar Apr 05 '20 09:04 kienerj

How do you make the comparison? Most of the times, and in this case in particular, it's best to compare the natural keys of the objects (usually the id attribute, but could be anything), instead of the object references. That is, instead of user is supervisor, it would be best if the check was user.id == supervisor.id

dfunckt avatar May 18 '20 16:05 dfunckt

Since my template is sending a OrderedDict I have to use access via named fields like user["id"] and can't use dot notation.

I think this is probably due to using a django rest framework viewset based on a serializer.

kienerj avatar May 26 '20 07:05 kienerj