admin.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from django.contrib import admin
  2. from django.contrib.admin.utils import quote
  3. from django.contrib.admin.views.main import ChangeList
  4. from django.contrib.auth import get_user_model
  5. from django.core.exceptions import ValidationError
  6. from django.urls import reverse
  7. from rest_framework.authtoken.models import Token, TokenProxy
  8. User = get_user_model()
  9. class TokenChangeList(ChangeList):
  10. """Map to matching User id"""
  11. def url_for_result(self, result):
  12. pk = result.user.pk
  13. return reverse('admin:%s_%s_change' % (self.opts.app_label,
  14. self.opts.model_name),
  15. args=(quote(pk),),
  16. current_app=self.model_admin.admin_site.name)
  17. class TokenAdmin(admin.ModelAdmin):
  18. list_display = ('key', 'user', 'created')
  19. fields = ('user',)
  20. ordering = ('-created',)
  21. actions = None # Actions not compatible with mapped IDs.
  22. def get_changelist(self, request, **kwargs):
  23. return TokenChangeList
  24. def get_object(self, request, object_id, from_field=None):
  25. """
  26. Map from User ID to matching Token.
  27. """
  28. queryset = self.get_queryset(request)
  29. field = User._meta.pk
  30. try:
  31. object_id = field.to_python(object_id)
  32. user = User.objects.get(**{field.name: object_id})
  33. return queryset.get(user=user)
  34. except (queryset.model.DoesNotExist, User.DoesNotExist, ValidationError, ValueError):
  35. return None
  36. def delete_model(self, request, obj):
  37. # Map back to actual Token, since delete() uses pk.
  38. token = Token.objects.get(key=obj.key)
  39. return super().delete_model(request, token)
  40. admin.site.register(TokenProxy, TokenAdmin)