kpsul/gestion/admin.py
Martin Pépin 7967983b5c More sophisticated admin site for the gestion app
- Nested inlines
- Limiting access to the events : you can only edit/create events linked to
  associations you for which you have the `<assoc>.buro` permission.
2017-06-25 17:57:23 +01:00

95 lines
2.2 KiB
Python

import nested_admin
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.forms.models import modelform_factory
from .models import (
Association, Profile, Club, Event, Location,
EventOption, EventCommentField, EventOptionChoice
)
# ---
# The user related stuff
# ---
class ProfileInline(admin.StackedInline):
model = Profile
inline_classes = ["collapse open"]
class UserProfileAdmin(UserAdmin):
inlines = [
ProfileInline,
]
admin.site.unregister(User)
admin.site.register(User, UserProfileAdmin)
# ---
# Clubs
# ---
admin.site.register(Club)
# ---
# Events
# ---
class EventOptionChoiceInline(nested_admin.NestedTabularInline):
model = EventOptionChoice
extra = 1
class EventOptionInline(nested_admin.NestedTabularInline):
model = EventOption
extra = 1
inlines = [EventOptionChoiceInline]
class EventCommentFieldInline(nested_admin.NestedTabularInline):
model = EventCommentField
extra = 1
@admin.register(Event)
class EventAdmin(nested_admin.NestedModelAdmin):
search_fields = ['title', 'location', 'description']
inlines = [
EventOptionInline,
EventCommentFieldInline,
]
def get_queryset(self, request):
"""Restrict the event you can edit"""
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
else:
assocs = Association.objects.filter(staff_group__user=request.user)
return qs.filter(associations__in=assocs)
def get_form(self, request, obj=None, **kwargs):
"""Restrict the applications you can attach to an event"""
if request.user.is_superuser:
return super().get_form(request, obj, **kwargs)
else:
assocs = Association.objects.filter(staff_group__user=request.user)
def formfield_callback(f, **kwargs):
if f.name == "associations":
kwargs["queryset"] = assocs
return f.formfield(**kwargs)
return modelform_factory(
Event,
exclude=[],
formfield_callback=formfield_callback
)
admin.site.register(Location)