Created
March 27, 2020 21:47
-
-
Save tclain/c3502a1b9c04f3f42966b75cab6fa0c0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CustomUserAdmin(UserAdmin): | |
inlines = (ProfileInline, ApiTokenInline) | |
list_display = ('username', 'free_evaluation_count', 'credits_balance', 'paid_evaluation_count',) | |
def get_readonly_fields(self, request, obj=None): | |
fields=super(UserAdmin, self).get_readonly_fields(request, obj) | |
return fields + ('free_evaluation_count', 'paid_evaluation_count', 'credits_balance',) | |
def get_fieldsets(self, request, obj=None): | |
if not obj: | |
return self.add_fieldsets | |
fieldsets = super(UserAdmin, self).get_fieldsets(request, obj) | |
return fieldsets + ( | |
('Usage de la plateforme', { | |
'fields': ('free_evaluation_count','paid_evaluation_count','credits_balance',) | |
} | |
), | |
) | |
def get_inline_instances(self, request, obj=None): | |
if not obj: | |
return list() | |
return super(CustomUserAdmin, self).get_inline_instances(request, obj) | |
def free_evaluation_count(self, obj): | |
''' | |
the count of free evaluations used by the user | |
''' | |
return obj.freeEvaluations.count() | |
def paid_evaluation_count(self, obj): | |
''' | |
the count of payed evaluations used by the user | |
''' | |
return obj.paidEvaluations.count() | |
def credits_balance(self, obj): | |
''' | |
get the balance of credits for the current user | |
''' | |
return obj.credit.quantity | |
def response_change(self, request, user): | |
''' | |
we have a special action that create api token | |
''' | |
if "_api_token_create" in request.POST: | |
return create_api_token_for_user_in_admin(request, user, self) | |
elif '_api_credits_add' in request.POST: | |
try: | |
credits_to_add_str = str(request.POST['_add_credits_value']) | |
credits_to_add = int(credits_to_add_str) | |
if credits_to_add > 0: | |
return add_credit_for_user_in_admin(request=request, user=user, quantity=credits_to_add, admin=self) | |
except Exception as e: | |
print(e) | |
self.message_user(request, "Le nombre de crédits est invalide", level=messages.ERROR) | |
elif '_api_credits_withdraw' in request.POST: | |
try: | |
credits_to_add_str = str(request.POST['_withdraw_credits_value']) | |
credits_to_add = int(credits_to_add_str) | |
if credits_to_add > 0: | |
return add_credit_for_user_in_admin(request=request, user=user, quantity=credits_to_add, admin=self) | |
except Exception as e: | |
print(e) | |
return super().response_change(request, user) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment