Self hosted FLOSS fitness/workout, nutrition and weight tracker
Refactor and simplify the pagination logic, add pagination to unit list
Roland Geider26f22da2549c
diff --git a/wger/manager/templates/template.html b/wger/manager/templates/template.htmlindex a489c2091..96f9e17b8 100644--- a/wger/manager/templates/template.html+++ b/wger/manager/templates/template.html@@ -132,7 +132,7 @@{% if user.is_authenticated %}<li><a href="{% url 'wger.nutrition.views.plan.overview' %}">{% trans "Nutrition plans" %}</a></li>{% endif %}- <li><a href="{% url 'wger.nutrition.views.ingredient.overview' %}">{% trans "Ingredient overview" %}</a></li>+ <li><a href="{% url 'ingredient-list' %}">{% trans "Ingredient overview" %}</a></li>{% if perms.exercises %}<li><a href="{% url 'weight-unit-list' %}">{% trans "Ingredient weight units" %}</a></li>{% endif %}diff --git a/wger/manager/templatetags/manager_extras.py b/wger/manager/templatetags/manager_extras.pyindex e4025ef73..276c60a8d 100644--- a/wger/manager/templatetags/manager_extras.py+++ b/wger/manager/templatetags/manager_extras.py@@ -1,4 +1,25 @@+# -*- coding: utf-8 -*-++# This file is part of Workout Manager.+#+# Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+from django import template+from django.core.paginator import EmptyPage, PageNotAnInteger++from wger.workout_manager.constants import PAGINATION_OBJECTS_PER_PAGE+from wger.workout_manager.constants import PAGINATION_MAX_TOTAL_PAGES+from wger.workout_manager.constants import PAGINATION_PAGES_AROUND_CURRENTregister = template.Library()@@ -24,10 +45,33 @@ def render_day(day):@register.inclusion_tag('tags/pagination.html')-def pagination(page, page_range):+def pagination(paginator, page):'''Renders the necessary links to paginating a long list'''++ # For very long lists (e.g. the English ingredient with more than 8000 items)+ # we muck around here to remove the pages not inmediately 'around' the current+ # one, otherwise we end up with a useless block with 300 pages.+ if paginator.num_pages > PAGINATION_MAX_TOTAL_PAGES:++ start_page = page.number - PAGINATION_PAGES_AROUND_CURRENT+ for i in range(page.number - PAGINATION_PAGES_AROUND_CURRENT, page.number + 1):+ if i > 0:+ start_page = i+ break++ end_page = page.number + PAGINATION_PAGES_AROUND_CURRENT+ for i in range(page.number, page.number + PAGINATION_PAGES_AROUND_CURRENT):+ if i > paginator.num_pages:+ end_page = i+ break++ page_range = range(start_page, end_page)+ else:+ page_range = paginator.page_range++ # Set the template variablesreturn {'page': page,'page_range': page_range}diff --git a/wger/nutrition/templates/ingredient/overview.html b/wger/nutrition/templates/ingredient/overview.htmlindex 4987dcdc4..35769cdf4 100644--- a/wger/nutrition/templates/ingredient/overview.html+++ b/wger/nutrition/templates/ingredient/overview.html@@ -30,9 +30,9 @@ $(document).ready(function() {{% block content %}-{% if ingredients %}+{% if ingredients_list %}<ul>- {% for ingredient in ingredients %}+ {% for ingredient in ingredients_list %}<li><a href="{{ ingredient.get_absolute_url }}">{{ ingredient.name }}</a></li>@@ -46,7 +46,7 @@ $(document).ready(function() {<div style="padding-top:3em;"></div>-{% pagination ingredients page_range %}+{% pagination paginator page_obj %}{% endblock %}diff --git a/wger/nutrition/templates/plan/overview.html b/wger/nutrition/templates/plan/overview.htmlindex 5b5fcc672..bd2656f1f 100644--- a/wger/nutrition/templates/plan/overview.html+++ b/wger/nutrition/templates/plan/overview.html@@ -57,7 +57,7 @@</p><p>- <a href="{% url 'wger.nutrition.views.ingredient.overview' %}" id="ingredient-overview">+ <a href="{% url 'ingredient-list' %}" id="ingredient-overview"><img src="{% static 'images/icons/list.svg' %}"width="32"height="32"diff --git a/wger/nutrition/templates/units/list.html b/wger/nutrition/templates/units/list.htmlindex ca766b3ec..8c304bd23 100644--- a/wger/nutrition/templates/units/list.html+++ b/wger/nutrition/templates/units/list.html@@ -45,8 +45,10 @@</tr>{% endfor %}</tbody>-</table>+</table>+<div style="padding-top:3em;"></div>+{% pagination paginator page_obj %}{% endblock %}diff --git a/wger/nutrition/tests/ingredient_overview.py b/wger/nutrition/tests/ingredient_overview.pyindex d2907f7db..f5241875d 100644--- a/wger/nutrition/tests/ingredient_overview.py+++ b/wger/nutrition/tests/ingredient_overview.py@@ -46,17 +46,29 @@ class OverviewPlanTestCase(WorkoutManagerTestCase):# Page existsself.user_logout()- response = self.client.get(reverse('wger.nutrition.views.ingredient.overview'))+ response = self.client.get(reverse('ingredient-list'))self.assertEqual(response.status_code, 200)- self.assertEqual(len(response.context['ingredients']), PAGINATION_OBJECTS_PER_PAGE)+ self.assertEqual(len(response.context['ingredients_list']), PAGINATION_OBJECTS_PER_PAGE)- response = self.client.get(reverse('wger.nutrition.views.ingredient.overview'),+ response = self.client.get(reverse('ingredient-list'),{'page': 2})self.assertEqual(response.status_code, 200)- self.assertEqual(len(response.context['ingredients']), PAGINATION_OBJECTS_PER_PAGE)+ self.assertEqual(len(response.context['ingredients_list']), PAGINATION_OBJECTS_PER_PAGE)rest_ingredients = Ingredient.objects.count() - 2 * PAGINATION_OBJECTS_PER_PAGE- response = self.client.get(reverse('wger.nutrition.views.ingredient.overview'),+ response = self.client.get(reverse('ingredient-list'),{'page': 3})self.assertEqual(response.status_code, 200)- self.assertEqual(len(response.context['ingredients']), rest_ingredients)+ self.assertEqual(len(response.context['ingredients_list']), rest_ingredients)++ # 'last' is a special case+ response = self.client.get(reverse('ingredient-list'), {'page': 'last'})+ self.assertEqual(response.status_code, 200)+ self.assertEqual(len(response.context['ingredients_list']), rest_ingredients)++ # Page does not exist+ response = self.client.get(reverse('ingredient-list'), {'page': 100})+ self.assertEqual(response.status_code, 404)++ response = self.client.get(reverse('ingredient-list'), {'page': 'foobar'})+ self.assertEqual(response.status_code, 404)diff --git a/wger/nutrition/tests/weight_unit.py b/wger/nutrition/tests/weight_unit.pyindex 29bea2698..9e0ff0ce5 100644--- a/wger/nutrition/tests/weight_unit.py+++ b/wger/nutrition/tests/weight_unit.py@@ -13,12 +13,17 @@# You should have received a copy of the GNU Affero General Public License# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.+from django.core.urlresolvers import reverse+from wger.nutrition.models import WeightUnit+from wger.manager.tests.testcase import WorkoutManagerTestCasefrom wger.manager.tests.testcase import WorkoutManagerDeleteTestCasefrom wger.manager.tests.testcase import WorkoutManagerEditTestCasefrom wger.manager.tests.testcase import WorkoutManagerAddTestCase+from wger.workout_manager.constants import PAGINATION_OBJECTS_PER_PAGE+class AddWeightUnitTestCase(WorkoutManagerAddTestCase):'''@@ -50,3 +55,43 @@ class EditWeightUnitTestCase(WorkoutManagerEditTestCase):url = 'weight-unit-edit'pk = 1data = {'name': 'A new name'}+++class WeightUnitOverviewTestCase(WorkoutManagerTestCase):+ '''+ Tests the ingredient unit overview page+ '''++ def test_overview(self):++ # Add more ingredient units so we can test the pagination+ self.user_login('admin')+ data = {"name": "A new, cool unit",+ "language": 2}+ for i in range(0, 50):+ self.client.post(reverse('weight-unit-add'), data)++ # Page exists and the pagination works+ response = self.client.get(reverse('weight-unit-list'))+ self.assertEqual(response.status_code, 200)+ self.assertEqual(len(response.context['unit_list']), PAGINATION_OBJECTS_PER_PAGE)++ response = self.client.get(reverse('weight-unit-list'), {'page': 2})+ self.assertEqual(response.status_code, 200)+ self.assertEqual(len(response.context['unit_list']), PAGINATION_OBJECTS_PER_PAGE)++ response = self.client.get(reverse('weight-unit-list'), {'page': 3})+ self.assertEqual(response.status_code, 200)+ self.assertEqual(len(response.context['unit_list']), 3)++ # 'last' is a special case+ response = self.client.get(reverse('weight-unit-list'), {'page': 'last'})+ self.assertEqual(response.status_code, 200)+ self.assertEqual(len(response.context['unit_list']), 3)++ # Page does not exist+ response = self.client.get(reverse('weight-unit-list'), {'page': 100})+ self.assertEqual(response.status_code, 404)++ response = self.client.get(reverse('weight-unit-list'), {'page': 'foobar'})+ self.assertEqual(response.status_code, 404)diff --git a/wger/nutrition/urls.py b/wger/nutrition/urls.pyindex 0c4d28b3c..2a1504325 100644--- a/wger/nutrition/urls.py+++ b/wger/nutrition/urls.py@@ -54,7 +54,9 @@ urlpatterns = patterns('wger.nutrition.views',url(r'^ingredient/add/$',permission_required('exercises.change_exercise')(ingredient.IngredientCreateView.as_view()),name='ingredient-add'),- url(r'^ingredient/overview/$', 'ingredient.overview'),+ url(r'^ingredient/overview/$',+ ingredient.IngredientListView.as_view(),+ name='ingredient-list'),url(r'^ingredient/(?P<id>\d+)/view/$', 'ingredient.view'),url(r'^ingredient/(?P<id>\d+)/view/(?P<slug>[-\w]+)/$', 'ingredient.view'),url(r'^ingredient/search/$',diff --git a/wger/nutrition/views/ingredient.py b/wger/nutrition/views/ingredient.pyindex a4dfe851e..aa5221c46 100644--- a/wger/nutrition/views/ingredient.py+++ b/wger/nutrition/views/ingredient.py@@ -55,9 +55,10 @@ from wger.manager.utils import load_languagefrom wger.manager.utils import load_ingredient_languagesfrom wger.workout_manager import get_version+from wger.workout_manager import helpersfrom wger.workout_manager.generic_views import YamlFormMixinfrom wger.workout_manager.generic_views import YamlDeleteMixin-from wger.workout_manager import helpers+from wger.workout_manager.constants import PAGINATION_OBJECTS_PER_PAGElogger = logging.getLogger('workout_manager.custom')@@ -65,27 +66,24 @@ logger = logging.getLogger('workout_manager.custom')# ************************# Ingredient functions# ************************-def overview(request):+class IngredientListView(ListView):'''Show an overview of all ingredients'''+ model = Ingredient+ template_name = 'ingredient/overview.html'+ context_object_name = 'ingredients_list'+ paginate_by = PAGINATION_OBJECTS_PER_PAGE- template_data = {}-- # Filter the ingredients the user will see by its language- # (the user can also want to see ingredients in English, see load_ingredient_languages)- languages = load_ingredient_languages(request)-- # Load the ingredients and paginate it- ingredients_list = Ingredient.objects.filter(language__in=languages)-- pagination = helpers.pagination(ingredients_list, request.GET.get('page'))- template_data['page_range'] = pagination['page_range']- template_data['ingredients'] = pagination['page']+ def get_queryset(self):+ '''+ Filter the ingredients the user will see by its language- return render_to_response('ingredient/overview.html',- template_data,- context_instance=RequestContext(request))+ (the user can also want to see ingredients in English, in addition to his+ native language, see load_ingredient_languages)+ '''+ languages = load_ingredient_languages(self.request)+ return Ingredient.objects.filter(language__in=languages)def view(request, id, slug=None):@@ -115,7 +113,7 @@ class IngredientDeleteView(YamlDeleteMixin, DeleteView):model = Ingredienttemplate_name = 'delete.html'- success_url = reverse_lazy('wger.nutrition.views.ingredient.overview')+ success_url = reverse_lazy('ingredient-list')messages = ugettext_lazy('Ingredient successfully deleted')# Send some additional data to the templatediff --git a/wger/nutrition/views/unit.py b/wger/nutrition/views/unit.pyindex 72f0521fb..0e43ba58b 100644--- a/wger/nutrition/views/unit.py+++ b/wger/nutrition/views/unit.py@@ -32,7 +32,7 @@ from wger.manager.utils import load_languagefrom wger.workout_manager.generic_views import YamlFormMixinfrom wger.workout_manager.generic_views import YamlDeleteMixin-+from wger.workout_manager.constants import PAGINATION_OBJECTS_PER_PAGElogger = logging.getLogger('workout_manager.custom')# ************************@@ -48,6 +48,7 @@ class WeightUnitListView(ListView):model = WeightUnittemplate_name = 'units/list.html'context_object_name = 'unit_list'+ paginate_by = PAGINATION_OBJECTS_PER_PAGEdef get_queryset(self):'''diff --git a/wger/workout_manager/helpers.py b/wger/workout_manager/helpers.pyindex 480e3cc07..97d9923ef 100644--- a/wger/workout_manager/helpers.py+++ b/wger/workout_manager/helpers.py@@ -17,62 +17,6 @@import decimalimport json-from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger--from wger.workout_manager.constants import PAGINATION_OBJECTS_PER_PAGE-from wger.workout_manager.constants import PAGINATION_MAX_TOTAL_PAGES-from wger.workout_manager.constants import PAGINATION_PAGES_AROUND_CURRENT---def pagination(object_list,- request_page,- paginator_class=Paginator,- objects_per_page=PAGINATION_OBJECTS_PER_PAGE,- max_total_pages=PAGINATION_MAX_TOTAL_PAGES,- pages_around_current=PAGINATION_PAGES_AROUND_CURRENT):- '''- Helper function to initialise the pagination.-- If the list is too long, only pages around the current one are shown.- '''-- paginator = paginator_class(object_list, objects_per_page)-- try:- paginated_page = paginator.page(request_page)- except PageNotAnInteger:- # If page is not an integer, deliver first page.- paginated_page = paginator.page(1)- except EmptyPage:- # If page is out of range (e.g. 9999), deliver last page of results.- paginated_page = paginator.page(paginator.num_pages)-- # For very long lists (e.g. the English ingredient with more than 8000 items)- # we muck around here to remove the pages not inmediately 'around' the current- # one, otherwise we end up with a which a useless block with 300 pages.- if paginator.num_pages > max_total_pages:-- start_page = paginated_page.number - pages_around_current- for i in range(paginated_page.number - pages_around_current, paginated_page.number + 1):- if i > 0:- start_page = i- break-- end_page = paginated_page.number + pages_around_current- for i in range(paginated_page.number, paginated_page.number + pages_around_current):- if i > paginator.num_pages:- end_page = i-- break-- page_range = range(start_page, end_page)- else:- page_range = paginator.page_range-- # OK, return- return({'page': paginated_page,- 'page_range': page_range})-class DecimalJsonEncoder(json.JSONEncoder):'''