PageRenderTime 274ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/apps/users/admin.py

https://bitbucket.org/giussepi/meals-tracker
Python | 193 lines | 192 code | 0 blank | 1 comment | 0 complexity | dd3e0b4f30a2bf03a298285bbb2d9c7f MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. """ users' Admin """
  3. from django.contrib import admin
  4. from django.shortcuts import get_object_or_404, render_to_response
  5. from django.template import RequestContext
  6. from .forms import AdminDailyConsumeForm, AdminMealForm, \
  7. AdminUserProfileForm, AdminAddUserProfileForm, InlineFoodMealForm
  8. from .models import UserProfile, Daily_Consume, Meal
  9. class UserProfileAdmin(admin.ModelAdmin):
  10. """ admin model that manages the profiles """
  11. form = AdminUserProfileForm
  12. list_display = ('__unicode__', 'user')
  13. list_display_links = ('__unicode__', 'user')
  14. # fields = (
  15. # 'height', 'weight', 'physical_activity', 'goal', 'gender', 'birthday',
  16. # 'body_fat_percent', 'bmr', 'tee', 'rdi_carbohydrates', 'rdi_protein',
  17. # 'rdi_fat', 'calories', 'user'
  18. # )
  19. fieldsets = (
  20. ('Basic Information', {
  21. 'fields': (('username', 'email'),
  22. 'user', ('first_name', 'last_name'),
  23. ('gender', 'birthday'), ('height', 'weight'),
  24. ('physical_activity', 'goal',),
  25. ('body_fat_percent', 'bmr', 'tee',))
  26. }),
  27. ('RDI', {
  28. 'fields': (
  29. 'recalculate_rdis',
  30. ('rdi_protein', 'rdi_carbohydrates'),
  31. ('rdi_fat', 'calories')
  32. )
  33. }),
  34. )
  35. actions = ['delete_objects_selected']
  36. class Media:
  37. """ model admin media files """
  38. js = ("users/js/jquery-1.8.0.min.js",
  39. "users/js/highcharts/highcharts.js",
  40. "users/js/rdi_pie_chart.js",
  41. "users/js/userprofile_basic_info.js",
  42. )
  43. def queryset(self, request):
  44. """
  45. if the user is a superuser returns all the queryset, else
  46. returns the queryset with the objects that belong to the current user
  47. """
  48. queryset = super(self.__class__, self).queryset(request)
  49. if request.user.is_superuser:
  50. return queryset
  51. return queryset.filter(user=request.user)
  52. def add_view(self, request, form_url='', extra_context=None):
  53. """ custom addition view """
  54. form = AdminAddUserProfileForm()
  55. if request.method == 'POST':
  56. form = AdminAddUserProfileForm(request.POST)
  57. if form.is_valid():
  58. return form.save(request)
  59. return render_to_response(
  60. 'admin/users/userprofile/add_form.html',
  61. {'form': form, 'app_label': 'users',
  62. 'changelist': 'admin:users_userprofile_changelist',
  63. 'verbose_name_plural': 'user profiles',
  64. 'verbose_name': 'user profile'},
  65. context_instance=RequestContext(request))
  66. def change_view(self, request, object_id, form_url='', extra_context=None):
  67. """
  68. adds the user of the profile, the pie chart and the weekly chart as a
  69. extra_context
  70. """
  71. extra_context = extra_context or {}
  72. userprofile = get_object_or_404(UserProfile, id=object_id)
  73. extra_context['profile_user'] = userprofile.user
  74. extra_context['rdis'] = userprofile.get_rdis()
  75. latest_daily_consume = userprofile.get_latest_daily_consume()
  76. if latest_daily_consume:
  77. extra_context['weekly_chart'] = latest_daily_consume.weekly_chart()
  78. return super(UserProfileAdmin, self).change_view(
  79. request, object_id, form_url, extra_context=extra_context)
  80. def has_add_permission(self, request):
  81. """ restricts the userprofile addition to only superusers """
  82. if request.user.is_superuser:
  83. return True
  84. return False
  85. def has_delete_permission(self, request, obj=None):
  86. """ restricts the userprofile deletion to only superusers """
  87. if request.user.is_superuser:
  88. return True
  89. return False
  90. def get_actions(self, request):
  91. """ restricts the delete action to only superusers """
  92. actions = super(UserProfileAdmin, self).get_actions(request)
  93. del actions['delete_selected']
  94. if not request.user.is_superuser:
  95. del actions['delete_objects_selected']
  96. return actions
  97. def delete_objects_selected(self, request, queryset):
  98. """
  99. deletes the objects selected using its user to create a cascade
  100. deletion
  101. Avoids the deletion of the self user.
  102. """
  103. for obj in queryset.exclude(id=request.user.userprofile.id):
  104. obj.user.delete()
  105. self.message_user(request, 'The selected userprofiles were deleted.')
  106. delete_objects_selected.short_description = 'Delete selected user profiles'
  107. def delete_model(self, request, obj):
  108. """ deletes the User of the profile """
  109. obj.user.delete()
  110. class Daily_ConsumeAdmin(admin.ModelAdmin):
  111. """ admin model that manages the daily consumes """
  112. date_hierarchy = 'date'
  113. form = AdminDailyConsumeForm
  114. class Media:
  115. """ model admin media files """
  116. css = {"all": ("users/css/admin/charts.css", )}
  117. def queryset(self, request):
  118. """
  119. returns the queryset with the objects that belong to the current user
  120. """
  121. return super(self.__class__, self).queryset(request).filter(
  122. user=request.user)
  123. def change_view(self, request, object_id, form_url='', extra_context=None):
  124. """ adds the pie chart as a extra_context """
  125. extra_context = extra_context or {}
  126. if object_id:
  127. consume = get_object_or_404(Daily_Consume, id=object_id)
  128. extra_context['chart'] = consume.data_total_intake_chart()
  129. extra_context['day_consume_chart'] = consume.day_consume_chart()
  130. return super(Daily_ConsumeAdmin, self).change_view(
  131. request, object_id, form_url, extra_context=extra_context)
  132. class FoodsInline(admin.TabularInline):
  133. """ admin model that manages the foods """
  134. model = Meal.foods.through
  135. form = InlineFoodMealForm
  136. class MealAdmin(admin.ModelAdmin):
  137. """ admin model that manages the meals """
  138. form = AdminMealForm
  139. inlines = [FoodsInline, ]
  140. class Media:
  141. """ model admin media files """
  142. css = {
  143. "all": (
  144. "users/css/admin/charts.css",
  145. )
  146. }
  147. def queryset(self, request):
  148. """
  149. returns the queryset with the objects that belong to the current user
  150. """
  151. return super(self.__class__, self).queryset(request).filter(
  152. daily_consume__user=request.user)
  153. def change_view(self, request, object_id, form_url='', extra_context=None):
  154. """ adds the pie chart as a extra_context """
  155. extra_context = extra_context or {}
  156. if object_id:
  157. meal = get_object_or_404(Meal, id=object_id)
  158. extra_context['chart'] = meal.daily_consume.\
  159. data_total_intake_chart()
  160. extra_context['meal_macronutrients'] = meal.\
  161. get_macronutrients_values()
  162. return super(MealAdmin, self).change_view(
  163. request, object_id, form_url, extra_context=extra_context)
  164. admin.site.register(UserProfile, UserProfileAdmin)
  165. admin.site.register(Daily_Consume, Daily_ConsumeAdmin)
  166. admin.site.register(Meal, MealAdmin)