[Django]-Is there a clean way to hide model attributes from some users in Django?

2๐Ÿ‘

โœ…

You will want add attribute, method, groups etc so you know if a user is restricted or not. Assuming you have user.is_restricted attribute:

class RestrictManager(models.Manager):

  def by_user(self,user):

     queryset = super(RestrictManager,self).get_queryset()
     if user.is_restricted:
       queryset = queryset.annotate(field_to_show=None) # field_to_show is a queryset field (not in any model)
     else:
       queryset = queryset.annotate(field_to_show=secret_field)

     return queryset

class MyRestrictedModel(models.Model):

   field1 = models.CharField...
   restricted_objects = RestrictManager()

In your code:

q = MyRestrictedModel.restricted_objects.by_user(self.request.user)
# Now use q as usual, q.all(), q.get(...), q.filter(...)

You can of course add more method like by_group etc, and even set objects=RestrictManager() to replace the objects default manager.

๐Ÿ‘คAviah Laor

0๐Ÿ‘

Probably you should use a django package that deals specifically with detailed permissions. See here all this kind of packages. The right for you โ€“ which has field level permissions management โ€“ is django-permissions. But there are others too.

๐Ÿ‘คdoru

Leave a comment