I have followed the user guide from the django-guardian docs to set up django-guardian. This has given me the possibility to control whether a group can view a specific class or not. This is the example from the django-guardian docs with an added field (customer):
class Task(models.Model):
summary = models.CharField(max_length=32)
content = models.TextField()
customer = models.CharField(max_length=80)
reported_by = models.ForeignKey(User)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
permissions = (
('view_task', 'View task'),
)
This (along with other code from the django-guardian docs example) allows me to give specific users and groups permission to "View Task" through the django admin. The thing is that I would like to restrict which tasks groups can see depending on who the customer is. An example could be that only consultants assigned to customer A can see tasks where task.customer = 'A'. Is there a way to set that up?
Any help is much appreciated.
This can be easily achieved with django-guardian, it just requires a bit more coding from your behalf.
For instance, to restrict which records a view returns in an admin changelist:
from django.contrib import admin
from myapp import models
from guardian.shortcuts import get_objects_for_user
@admin.register(models.Task)
class TaskAdmin(admin.ModelAdmin):
# ...
def get_queryset(self, request):
qs = super(TaskAdmin, self).get_queryset(request)
tasks = get_objects_for_user(request.user, 'myapp.view_task', klass=models.Task)
return qs.filter(task_id__in=tasks.values_list('id'))
Similary, you can do this in any regular view.