med/sporz/admin.py

73 lines
2.3 KiB
Python
Raw Normal View History

2019-08-15 09:36:39 +00:00
# -*- mode: python; coding: utf-8 -*-
# Copyright (C) 2017-2019 by BDE ENS Paris-Saclay
# SPDX-License-Identifier: GPL-3.0-or-later
from django.contrib import admin
2019-08-16 13:05:10 +00:00
from django.contrib.auth import get_user_model
from django.db.models import Q
2019-08-15 09:36:39 +00:00
from med.admin import admin_site
from .models import GameSave, Player
class PlayerInline(admin.TabularInline):
model = Player
class GameSaveAdmin(admin.ModelAdmin):
inlines = [PlayerInline, ]
list_display = ('__str__', 'game_master', 'game_has_ended')
date_hierarchy = 'created_at'
2019-08-16 13:05:10 +00:00
autocomplete_fields = ('game_master',)
2019-08-15 09:36:39 +00:00
def has_change_permission(self, request, obj=None):
"""
If user is game master then authorize edit
"""
if obj and obj.game_master == request.user:
return True
return super().has_change_permission(request, obj)
def has_delete_permission(self, request, obj=None):
"""
If user is game master then authorize deletion
"""
if obj and obj.game_master == request.user:
return True
return super().has_delete_permission(request, obj)
2019-08-16 12:34:16 +00:00
def add_view(self, request, form_url='', extra_context=None):
"""
Autoselect game master when creating a new game
"""
# Make GET data mutable
data = request.GET.copy()
data['game_master'] = request.user
request.GET = data
return super().add_view(request, form_url, extra_context)
2019-08-16 13:05:10 +00:00
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""
Authorize game master change only if user can see all users
"""
if db_field.name == 'game_master':
if not request.user.has_perm('users.view_user'):
kwargs['queryset'] = get_user_model().objects.filter(
username=request.user.username)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
def get_queryset(self, request):
"""
List all game save only if user has view permission
else, list only own games and ended games
"""
queryset = super().get_queryset(request)
if request.user.has_perm('sporz.view_gamesave'):
return queryset
return queryset.filter(
Q(game_master=request.user) | Q(game_has_ended=True)
)
2019-08-15 09:36:39 +00:00
admin_site.register(GameSave, GameSaveAdmin)