2

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.

Wessi
  • 1,702
  • 4
  • 36
  • 69

1 Answers1

2

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.

Wtower
  • 18,848
  • 11
  • 103
  • 80
  • Thank you so much for the response. Unfortunately I get an error message: "raise AlreadyRegistered('The model %s is already registered' % model.__name__) django.contrib.admin.sites.AlreadyRegistered: The model Task is already registered" Any idea what causes this? – Wessi Jul 04 '16 at 13:36
  • 1
    Welcome. This tells you that you have registered somewhere else the ModelAdmin for that particular model. You have to either amend the changes in there, or unregister it before registering it again. This is a totally different matter however. – Wtower Jul 04 '16 at 15:04
  • I found the mistake. My bad. Thanks. I now get another error however: "FieldError at /admin/app/task/ Cannot resolve keyword 'task' into field. Choices are: summary, content , customer, reported_by, created_at" – Wessi Jul 04 '16 at 16:42
  • 1
    Welcome. The code attached is a mere sample. You need to understand the fundamentals of Django in any case such as the ORM. For instance, it should possibly be `task_id__in`. – Wtower Jul 04 '16 at 17:18