admin.py 1.28 KB
Newer Older
Aymeric Barantal's avatar
Aymeric Barantal committed
1 2
from django.contrib import admin

okhin's avatar
okhin committed
3
from picampaign.organization.models import FeedbackCategory
4
from picampaign.feedback.models import Feedback
Aymeric Barantal's avatar
Aymeric Barantal committed
5

okhin's avatar
okhin committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
class FeedbackFilterByCategory(admin.SimpleListFilter):
    title = 'category'
    parameter_name = 'category'

    def lookups(self, request, model_admin):
        if request.user.is_superuser:
            feedbacks = Feedback.objects.all().values_list('category__id', 'category__name')
        else:
            user_orgs = [x.id for x in request.user.organizations.all()]
            feedbacks = Feedback.objects.filter(category__organisation__in=user_orgs).values_list('category_id', 'category_name')

        return ((f[0], f[1],) for f in sorted(set(feedbacks), key=lambda f: f[1]))

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(category__id=self.value())
        return queryset

class FeedbackAdmin(admin.ModelAdmin):
    list_filter = (FeedbackFilterByCategory,)

    def get_queryset(self, request):
        qs = super(FeedbackAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        user_orgs = [x.id for x in request.user.organizations.all()]
        return qs.filter(category__organization__in=user_orgs)

admin.site.register(Feedback, FeedbackAdmin)