Z
Z
zigen2016-05-31 08:51:31
Django
zigen, 2016-05-31 08:51:31

How to limit visibility of model instance fields in Django?

Good afternoon.
A rather unusual task for Django, it seems to me.
Have a User model and allow a Supply data model

class Supply(model.Model):
    name = models.CharField(...)
    field1 = models.CharField(...)
    field2 = models.CharField(...)
    field3 = models.CharField(...)

It is necessary to make an interface in the admin panel to limit the visibility of any field of a certain delivery for a specific user.
It occurred to me to create an intermediate model in which to specify a specific user, delivery and fields that he should not see (by default he sees everything):
class IntermediateTable(models.Model):
    user = models.ForeignKey(User)
    supply = models.ForeignKey(Supply)
    access = models.ManyToManyField(Choices, null=True, blank=True)

In the choice, add the field names of the Supply model.
class Choices(models.Model):
  description = models.CharField(max_length=300)

Then filter the Querieset in view. I smell hellish hardcode, tell me a more elegant solution

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan, 2016-05-31
@ATNC

Можно попробовать в admin.py переопределить метод get_form и при инициализации формы сделать там проверку на юзера, например:

class SupplyAdmin(admin.ModelAdmin):
   available_fields = ('name', 'field1', 'field2')
   hidden_fields = ('field3',)
   def get_form(self, request, obj, **kwargs):                             
       if request.user.username == '[email protected]':                                            
           self.fields = self.available_fields + self.hidden_fields         
       else:                                                                    
           self.fields = self.available_fields

        return super(SupplyAdmin, self).get_form(request, obj, **kwargs)

Алексей Сергеев, 2016-05-31
@SergeevAI

Можно так попробовать:

class Choices(models.Model):
    description = models.CharField(max_length=300)
    users = models.ManyToManyField(User)

def some_view(request):
    list = [item for item in Choices.objects.all() if request.user in item.users.all() ]
    return render(request, 'template.html', locals() )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question