Self hosted FLOSS fitness/workout, nutrition and weight tracker
Split the views from the nutrition app into individual files
Roland Geidered6174a89725
diff --git a/wger/manager/templates/index.html b/wger/manager/templates/index.htmlindex cbbc760a2..e611f3b64 100644--- a/wger/manager/templates/index.html+++ b/wger/manager/templates/index.html@@ -49,7 +49,7 @@<h3>{% trans "Nutrition plan"%}</h3>{% if plan %}- <a href="{% url 'wger.nutrition.views.view' plan.id %}">+ <a href="{% url 'wger.nutrition.views.plan.view' plan.id %}">{% if plan.description %}{{ plan.description }}{% else %}@@ -104,7 +104,7 @@<div class="ym-g50 ym-gr"><div class="ym-gbox-right"><p>- <a href="{% url 'wger.nutrition.views.add' %}">+ <a href="{% url 'wger.nutrition.views.plan.add' %}"><img src="{% static 'images/icons/new.svg' %}"width="32"height="32"diff --git a/wger/manager/templates/template.html b/wger/manager/templates/template.htmlindex a06022ec6..c98117de9 100644--- a/wger/manager/templates/template.html+++ b/wger/manager/templates/template.html@@ -123,14 +123,14 @@{% endif %}<li class="dropdown {% if active_tab == 'nutrition' %}active{% endif %}">- <a href="{% url 'wger.nutrition.views.overview' %}"+ <a href="{% url 'wger.nutrition.views.plan.overview' %}"class="dropdown-toggle"data-toggle="dropdown">{% trans "Nutrition" %} <b class="caret"></b></a><ul class="dropdown-menu">{% if user.is_authenticated %}- <li><a href="{% url 'wger.nutrition.views.overview' %}">{% trans "Nutrition plans" %}</a></li>+ <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 'wger.nutrition.views.ingredient.ingredient_overview' %}">{% 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/tests/index.py b/wger/manager/tests/index.pyindex c0310554c..7dca8d924 100644--- a/wger/manager/tests/index.py+++ b/wger/manager/tests/index.py@@ -74,7 +74,7 @@ class DashboardTestCase(WorkoutManagerTestCase):## 2. Add a nutrition plan#- self.client.get(reverse('wger.nutrition.views.add'))+ self.client.get(reverse('wger.nutrition.views.plan.add'))response = self.client.get(reverse('dashboard'))if logged_in:diff --git a/wger/nutrition/models.py b/wger/nutrition/models.pyindex b088f3469..b7e075201 100644--- a/wger/nutrition/models.py+++ b/wger/nutrition/models.py@@ -57,7 +57,7 @@ class NutritionPlan(models.Model):'''Returns the canonical URL to view this object'''- return reverse('wger.nutrition.views.view', kwargs={'id': self.id})+ return reverse('wger.nutrition.views.plan.view', kwargs={'id': self.id})def get_nutritional_values(self):# Sum the nutrional info@@ -156,8 +156,8 @@ class Ingredient(models.Model):'''Returns the canonical URL to view this object'''- return reverse('wger.nutrition.views.ingredient_view', kwargs={'id': self.id,- 'slug': slugify(self.name)})+ return reverse('wger.nutrition.views.ingredient.ingredient_view',+ kwargs={'id': self.id, 'slug': slugify(self.name)})def __unicode__(self):'''diff --git a/wger/nutrition/templates/edit_meal_item.html b/wger/nutrition/templates/edit_meal_item.htmlindex 2d686d7f2..ea7a45772 100644--- a/wger/nutrition/templates/edit_meal_item.html+++ b/wger/nutrition/templates/edit_meal_item.html@@ -24,7 +24,7 @@ $(document).ready(function() {<h2>{% trans "Edit meal item" %}</h2>-<form action="{% url 'wger.nutrition.views.edit_meal_item' plan.id meal.id meal_item.id%}{% if js_active %}?js=on{% endif %}"+<form action="{% url 'wger.nutrition.views.ingredient.edit_meal_item' plan.id meal.id meal_item.id%}{% if js_active %}?js=on{% endif %}"method="post"class="ym-form">{% csrf_token %}diff --git a/wger/nutrition/templates/ingredient_search.html b/wger/nutrition/templates/ingredient_search.htmlindex 49867075b..aed1d8a94 100644--- a/wger/nutrition/templates/ingredient_search.html+++ b/wger/nutrition/templates/ingredient_search.html@@ -15,7 +15,7 @@<h2>{% trans "Search results" %} - "{{ search_term }}"</h2>-<form action="{% url 'wger.nutrition.views.ingredient_search' %}"+<form action="{% url 'wger.nutrition.views.ingredient.ingredient_search' %}"method="get"id="ingredient_search_form">{% csrf_token %}@@ -24,7 +24,7 @@<ul>{% for ingredient in ingredients %}- <li><a href="{% url 'wger.nutrition.views.ingredient_view' ingredient.id %}">{{ ingredient.name }}</a></li>+ <li><a href="{% url 'wger.nutrition.views.ingredient.ingredient_view' ingredient.id %}">{{ ingredient.name }}</a></li>{% endfor %}</ul>diff --git a/wger/nutrition/templates/nutrition_overview.html b/wger/nutrition/templates/nutrition_overview.htmlindex ecb8bcd33..54c14d322 100644--- a/wger/nutrition/templates/nutrition_overview.html+++ b/wger/nutrition/templates/nutrition_overview.html@@ -19,7 +19,7 @@{% for plan in plans %}<tr><td>- <a href="{% url 'wger.nutrition.views.view' plan.id %}">+ <a href="{% url 'wger.nutrition.views.plan.view' plan.id %}">{% if plan.description %}{{ plan.description }}{% else %}@@ -47,7 +47,7 @@{% block sidebar%}<h3>{% trans "Options" %}</h3><p>- <a href="{% url 'wger.nutrition.views.add' %}" id="nutrition-create-new">+ <a href="{% url 'wger.nutrition.views.plan.add' %}" id="nutrition-create-new"><img src="{% static 'images/icons/new.svg' %}"width="32"height="32"@@ -57,7 +57,7 @@</p><p>- <a href="{% url 'wger.nutrition.views.ingredient_overview' %}" id="ingredient-overview">+ <a href="{% url 'wger.nutrition.views.ingredient.ingredient_overview' %}" id="ingredient-overview"><img src="{% static 'images/icons/list.svg' %}"width="32"height="32"diff --git a/wger/nutrition/templates/view_nutrition_plan.html b/wger/nutrition/templates/view_nutrition_plan.htmlindex 220d2278e..b991370c1 100644--- a/wger/nutrition/templates/view_nutrition_plan.html+++ b/wger/nutrition/templates/view_nutrition_plan.html@@ -61,7 +61,7 @@ $(document).ready(function() {{% if meal.time %} – {{meal.time|time:"H:i"}}{% endif %}<div class="editoptions">- <a href="{% url 'wger.nutrition.views.delete_meal' meal.id %}"+ <a href="{% url 'wger.nutrition.views.meal.delete_meal' meal.id %}"title="{% trans 'Delete' %}"><img src="{% static 'images/icons/trash.svg' %}"width="16"@@ -78,7 +78,7 @@ $(document).ready(function() {alt="{% trans 'Edit meal' %}"title="{% trans 'Edit meal' %}"></a>- <a href="{% url 'wger.nutrition.views.edit_meal_item' plan.id meal.id None %}"+ <a href="{% url 'wger.nutrition.views.ingredient.edit_meal_item' plan.id meal.id None %}"title="{% trans 'Add' %}"class="modal-dialog edit-meal"><img src="{% static 'images/icons/add.svg' %}"@@ -102,7 +102,7 @@ $(document).ready(function() {{{ item.ingredient.name }}<span class="editoptions">- <a href="{% url 'wger.nutrition.views.delete_meal_item' item.id %}"+ <a href="{% url 'wger.nutrition.views.ingredient.delete_meal_item' item.id %}"title="{% trans 'Delete' %}"class="delete-mealitem"><img src="{% static 'images/icons/trash.svg' %}"@@ -110,7 +110,7 @@ $(document).ready(function() {height="16"alt="{% trans 'Delete' %}"></a>- <a href="{% url 'wger.nutrition.views.edit_meal_item' plan.id meal.id item.id %}"+ <a href="{% url 'wger.nutrition.views.ingredient.edit_meal_item' plan.id meal.id item.id %}"title="{% trans 'Edit' %}"class="modal-dialog edit-meal edit-mealitem"><img src="{% static 'images/icons/edit.svg' %}"@@ -123,7 +123,7 @@ $(document).ready(function() {{% empty %}<div class="box warning ingredient-box-warning">{% trans "No items for this meal." %}- <a href="{% url 'wger.nutrition.views.edit_meal_item' plan.id meal.id item.id %}"+ <a href="{% url 'wger.nutrition.views.ingredient.edit_meal_item' plan.id meal.id item.id %}"title="{% trans 'Edit' %}"class="modal-dialog edit-meal">{% trans "Add one now."%}@@ -239,7 +239,7 @@ $(document).ready(function() {<h3>{% trans "Options" %}</h3><p>-<a href="{% url 'wger.nutrition.views.export_pdf' plan.id %}"+<a href="{% url 'wger.nutrition.views.plan.export_pdf' plan.id %}"target="_blank"><img src="{% static 'images/icons/save.svg' %}"width="32"diff --git a/wger/nutrition/tests/copy_plan.py b/wger/nutrition/tests/copy_plan.pyindex ba9b8f685..3de8f20b7 100644--- a/wger/nutrition/tests/copy_plan.py+++ b/wger/nutrition/tests/copy_plan.py@@ -49,7 +49,7 @@ class CopyPlanTestCase(WorkoutManagerTestCase):self.assertEqual(count_after, 7)# Test accessing the copied workout- response = self.client.get(reverse('wger.nutrition.views.view', kwargs={'id': 4}))+ response = self.client.get(reverse('wger.nutrition.views.plan.view', kwargs={'id': 4}))if fail:self.assertIn(response.status_code, (404, 302))diff --git a/wger/nutrition/tests/ingredient.py b/wger/nutrition/tests/ingredient.pyindex 286829a0a..415ecaeb5 100644--- a/wger/nutrition/tests/ingredient.py+++ b/wger/nutrition/tests/ingredient.py@@ -83,7 +83,7 @@ class IngredientDetailTestCase(WorkoutManagerTestCase):Tests the ingredient details page'''- response = self.client.get(reverse('wger.nutrition.views.ingredient_view',+ response = self.client.get(reverse('wger.nutrition.views.ingredient.ingredient_view',kwargs={'id': 6}))self.assertEqual(response.status_code, 200)@@ -100,7 +100,7 @@ class IngredientDetailTestCase(WorkoutManagerTestCase):self.assertNotContains(response, 'Delete ingredient')# Non-existent ingredients throw a 404.- response = self.client.get(reverse('wger.nutrition.views.ingredient_view',+ response = self.client.get(reverse('wger.nutrition.views.ingredient.ingredient_view',kwargs={'id': 42}))self.assertEqual(response.status_code, 404)diff --git a/wger/nutrition/tests/ingredient_overview.py b/wger/nutrition/tests/ingredient_overview.pyindex f1b4046f2..54840eda8 100644--- a/wger/nutrition/tests/ingredient_overview.py+++ b/wger/nutrition/tests/ingredient_overview.py@@ -46,15 +46,17 @@ class OverviewPlanTestCase(WorkoutManagerTestCase):# Page existsself.user_logout()- response = self.client.get(reverse('wger.nutrition.views.ingredient_overview'))+ response = self.client.get(reverse('wger.nutrition.views.ingredient.ingredient_overview'))self.assertEqual(response.status_code, 200)self.assertEqual(len(response.context['ingredients']), PAGINATION_OBJECTS_PER_PAGE)- response = self.client.get(reverse('wger.nutrition.views.ingredient_overview') + '?page=2')+ response = self.client.get(reverse('wger.nutrition.views.ingredient.ingredient_overview')+ + '?page=2')self.assertEqual(response.status_code, 200)self.assertEqual(len(response.context['ingredients']), PAGINATION_OBJECTS_PER_PAGE)rest_ingredients = Ingredient.objects.count() - 2 * PAGINATION_OBJECTS_PER_PAGE- response = self.client.get(reverse('wger.nutrition.views.ingredient_overview') + '?page=3')+ response = self.client.get(reverse('wger.nutrition.views.ingredient.ingredient_overview')+ + '?page=3')self.assertEqual(response.status_code, 200)self.assertEqual(len(response.context['ingredients']), rest_ingredients)diff --git a/wger/nutrition/tests/pdf.py b/wger/nutrition/tests/pdf.pyindex f9967a32f..779c13aef 100644--- a/wger/nutrition/tests/pdf.py+++ b/wger/nutrition/tests/pdf.py@@ -28,7 +28,8 @@ class NutritionalPlanPdfExportTestCase(WorkoutManagerTestCase):'''# Create a workout- response = self.client.get(reverse('wger.nutrition.views.export_pdf', kwargs={'id': 4}))+ response = self.client.get(reverse('wger.nutrition.views.plan.export_pdf',+ kwargs={'id': 4}))if fail:self.assertIn(response.status_code, (404, 302))diff --git a/wger/nutrition/urls.py b/wger/nutrition/urls.pyindex cd5b05e88..7662089a8 100644--- a/wger/nutrition/urls.py+++ b/wger/nutrition/urls.py@@ -2,32 +2,34 @@ from django.conf.urls import patterns, urlfrom django.contrib.auth.decorators import permission_requiredfrom django.contrib.auth.decorators import login_required-from wger.nutrition.views import IngredientCreateView-from wger.nutrition.views import IngredientEditView-from wger.nutrition.views import IngredientDeleteView-from wger.nutrition.views import PlanDeleteView-from wger.nutrition.views import PlanEditView-from wger.nutrition.views import MealCreateView-from wger.nutrition.views import MealEditView--from wger.nutrition.views import WeightUnitListView-from wger.nutrition.views import WeightUnitCreateView-from wger.nutrition.views import WeightUnitDeleteView-from wger.nutrition.views import WeightUnitUpdateView--from wger.nutrition.views import WeightUnitIngredientCreateView-from wger.nutrition.views import WeightUnitIngredientUpdateView-from wger.nutrition.views import WeightUnitIngredientDeleteView+from wger.nutrition.views.ingredient import IngredientCreateView+from wger.nutrition.views.ingredient import IngredientEditView+from wger.nutrition.views.ingredient import IngredientDeleteView++from wger.nutrition.views.plan import PlanDeleteView+from wger.nutrition.views.plan import PlanEditView++from wger.nutrition.views.meal import MealCreateView+from wger.nutrition.views.meal import MealEditView++from wger.nutrition.views.unit import WeightUnitListView+from wger.nutrition.views.unit import WeightUnitCreateView+from wger.nutrition.views.unit import WeightUnitDeleteView+from wger.nutrition.views.unit import WeightUnitUpdateView++from wger.nutrition.views.unit_ingredient import WeightUnitIngredientCreateView+from wger.nutrition.views.unit_ingredient import WeightUnitIngredientUpdateView+from wger.nutrition.views.unit_ingredient import WeightUnitIngredientDeleteViewurlpatterns = patterns('wger.nutrition.views',- url(r'^overview/$', 'overview'),+ url(r'^overview/$', 'plan.overview'),# Plans- url(r'^add/$', 'add'),- url(r'^(?P<id>\d+)/view/$', 'view'),+ url(r'^add/$', 'plan.add'),+ url(r'^(?P<id>\d+)/view/$', 'plan.view'),url(r'^(?P<pk>\d+)/copy/$',- 'copy',+ 'plan.copy',name='nutrition-copy'),url(r'^(?P<pk>\d+)/delete/$',@@ -36,7 +38,7 @@ urlpatterns = patterns('wger.nutrition.views',url(r'^(?P<pk>\d+)/edit/$',login_required(PlanEditView.as_view()),name='nutrition-edit'),- url(r'^(?P<id>\d+)/pdf/$', 'export_pdf'),+ url(r'^(?P<id>\d+)/pdf/$', 'plan.export_pdf'),# Mealsurl(r'^(?P<plan_pk>\d+)/meal/add/$',@@ -46,11 +48,11 @@ urlpatterns = patterns('wger.nutrition.views',login_required(MealEditView.as_view()),name='meal-edit'),- url(r'^(?P<id>\d+)/delete/meal/$', 'delete_meal'),+ url(r'^(?P<id>\d+)/delete/meal/$', 'meal.delete_meal'),# Meal items- url(r'^(?P<id>\d+)/edit/meal/(?P<meal_id>\d+)/item/(?P<item_id>\w*)$', 'edit_meal_item'),- url(r'^delete/meal/item/(?P<item_id>\d+)$', 'delete_meal_item'),+ url(r'^(?P<id>\d+)/edit/meal/(?P<meal_id>\d+)/item/(?P<item_id>\w*)$', 'ingredient.edit_meal_item'),+ url(r'^delete/meal/item/(?P<item_id>\d+)$', 'ingredient.delete_meal_item'),# Ingredientsurl(r'^ingredient/(?P<pk>\d+)/delete/$',@@ -65,10 +67,10 @@ urlpatterns = patterns('wger.nutrition.views',permission_required('exercises.change_exercise')(IngredientCreateView.as_view()),name='ingredient-add'),- url(r'^ingredient/overview/$', 'ingredient_overview'),- 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/$', 'ingredient_search'),+ url(r'^ingredient/overview/$', 'ingredient.ingredient_overview'),+ url(r'^ingredient/(?P<id>\d+)/view/$', 'ingredient.ingredient_view'),+ url(r'^ingredient/(?P<id>\d+)/view/(?P<slug>[-\w]+)/$', 'ingredient.ingredient_view'),+ url(r'^ingredient/search/$', 'ingredient.ingredient_search'),# Ingredient unitsurl(r'^ingredient/unit/list/$',@@ -86,7 +88,7 @@ urlpatterns = patterns('wger.nutrition.views',# Ingredient to weight units cross table- url(r'^ingredient/(?P<ingredient_pk>\d+)/unit/add/$',+ url(r'^ingredient/unit-to-ingredient/add/(?P<ingredient_pk>\d+)/$',permission_required('exercises.change_exercise')(WeightUnitIngredientCreateView.as_view()),name='weight-unit-ingredient-add'),url(r'^ingredient/unit-to-ingredient/(?P<pk>\d+)/edit/$',diff --git a/wger/nutrition/views.py b/wger/nutrition/views.pydeleted file mode 100644index 02e51391d..000000000--- a/wger/nutrition/views.py+++ /dev/null@@ -1,721 +0,0 @@-# -*- 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-import logging-import json--from django.template import RequestContext-from django.shortcuts import render_to_response-from django.shortcuts import get_object_or_404-from django.http import HttpResponse-from django.http import HttpResponseRedirect-from django.http import HttpResponseForbidden-from django.core.context_processors import csrf-from django.core.urlresolvers import reverse-from django.core.urlresolvers import reverse_lazy-from django.contrib.auth.decorators import login_required-from django.forms import ModelForm-from django.utils.translation import ugettext as _-from django.utils.translation import ugettext_lazy---from django.views.generic import DeleteView-from django.views.generic import CreateView-from django.views.generic import UpdateView-from django.views.generic import ListView---from wger.nutrition.models import NutritionPlan-from wger.nutrition.models import Meal-from wger.nutrition.models import MealItem-from wger.nutrition.models import Ingredient-from wger.nutrition.models import WeightUnit-from wger.nutrition.models import IngredientWeightUnit--from reportlab.lib.styles import getSampleStyleSheet-from reportlab.lib.pagesizes import A4, cm-from reportlab.platypus import Paragraph, SimpleDocTemplate, Table-from reportlab.lib import colors--from wger.manager.utils import load_language-from wger.manager.utils import load_ingredient_languages--from wger.workout_manager import get_version-from wger.workout_manager.generic_views import YamlFormMixin-from wger.workout_manager.generic_views import YamlDeleteMixin-from wger.workout_manager import helpers---logger = logging.getLogger('workout_manager.custom')---# ************************-# Plan functions-# ************************--class PlanForm(ModelForm):- class Meta:- model = NutritionPlan- exclude = ('user', 'language', )---@login_required-def overview(request):- template_data = {}- template_data.update(csrf(request))-- plans = NutritionPlan.objects.filter(user=request.user)- template_data['plans'] = plans-- return render_to_response('nutrition_overview.html',- template_data,- context_instance=RequestContext(request))---@login_required-def add(request):- '''- Add a new nutrition plan and redirect to its page- '''-- plan = NutritionPlan()- plan.user = request.user- plan.language = load_language()- plan.save()-- return HttpResponseRedirect(reverse('wger.nutrition.views.view', kwargs={'id': plan.id}))---class PlanDeleteView(YamlDeleteMixin, DeleteView):- '''- Generic view to delete a nutritional plan- '''-- model = NutritionPlan- success_url = reverse_lazy('wger.nutrition.views.overview')- title = ugettext_lazy('Delete nutritional plan?')- form_action_urlname = 'nutrition-delete'---class PlanEditView(YamlFormMixin, UpdateView):- '''- Generic view to update an existing nutritional plan- '''-- model = NutritionPlan- form_class = PlanForm- title = ugettext_lazy('Add a new nutritional plan')- form_action_urlname = 'nutrition-edit'---@login_required-def view(request, id):- '''- Show the nutrition plan with the given ID- '''- template_data = {}-- plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)- template_data['plan'] = plan-- # Load the language and pass it to the template- language = load_language()- template_data['language'] = language-- # Get the nutrional info-- template_data['nutritional_data'] = plan.get_nutritional_values()-- return render_to_response('view_nutrition_plan.html',- template_data,- context_instance=RequestContext(request))---@login_required-def copy(request, pk):- '''- Copy the nutrition plan- '''-- plan = get_object_or_404(NutritionPlan, pk=pk, user=request.user)-- # Copy plan- meals = plan.meal_set.all()-- plan_copy = plan- plan_copy.pk = None- plan_copy.save()-- # Copy the meals- for meal in meals:- meal_items = meal.mealitem_set.all()-- meal_copy = meal- meal_copy.pk = None- meal_copy.plan = plan_copy- meal_copy.save()-- # Copy the individual meal entries- for item in meal_items:- item_copy = item- item_copy.pk = None- item_copy.meal = meal_copy- item.save()-- # Redirect- return HttpResponseRedirect(reverse('wger.nutrition.views.view', kwargs={'id': plan.id}))---@login_required-def export_pdf(request, id):- '''- Generates a PDF with the contents of a nutrition plan-- See also- * http://www.blog.pythonlibrary.org/2010/09/21/reportlab- * http://www.reportlab.com/apis/reportlab/dev/platypus.html- '''-- #Load the workout- plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)-- # Create the HttpResponse object with the appropriate PDF headers.- response = HttpResponse(mimetype='application/pdf')-- # Translators: translation can only have ASCII characters- response['Content-Disposition'] = 'attachment; filename=%s.pdf' % _('nutritional-plan')-- # Create the PDF object, using the response object as its "file."- doc = SimpleDocTemplate(response,- pagesize=A4,- title=_('Workout'),- author=_('Workout Manager'),- subject=_('Nutritional plan %s') % request.user.username)-- # Background colour for header- # Reportlab doesn't use the HTML hexadecimal format, but has a range of- # 0 till 1, so we have to convert here.- header_colour = colors.Color(int('73', 16) / 255.0,- int('8a', 16) / 255.0,- int('5f', 16) / 255.0)-- # container for the 'Flowable' objects- elements = []-- styleSheet = getSampleStyleSheet()- data = []-- # Iterate through the Plan- meal_markers = []- ingredient_markers = []-- # Meals- i = 0- for meal in plan.meal_set.select_related():- i += 1-- meal_markers.append(len(data))-- if not meal.time:- P = Paragraph('<para align="center"><strong>%(meal_nr)s</strong></para>' %- {'meal_nr': i},- styleSheet["Normal"])- else:- P = Paragraph('<para align="center"><strong>%(meal_nr)s - '- '%(meal_time)s</strong></para>' %- {'meal_nr': i,- 'meal_time': meal.time.strftime("%H:%M")},- styleSheet["Normal"])- data.append([P])-- # Ingredients- for item in meal.mealitem_set.select_related():- ingredient_markers.append(len(data))-- P = Paragraph('<para>%s</para>' % item.ingredient.name,- styleSheet["Normal"])- data.append(["%sg" % item.amount_gramm, P])-- # Set general table styles-- #('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),- #('BOX', (0,0), (-1,-1), 0.25, colors.black)- table_style = []-- # Set specific styles, e.g. background for title cells- for marker in meal_markers:- # Set background colour for headings- table_style.append(('BACKGROUND', (0, marker), (-1, marker), header_colour))- table_style.append(('BOX', (0, marker), (-1, marker), 1.25, colors.black))-- # Make the headings span the whole width- table_style.append(('SPAN', (0, marker), (-1, marker)))-- t = Table(data, style=table_style)-- # Manually set the width of the columns- t._argW[0] = 2 * cm-- # Set the title (if available)- if plan.description:- P = Paragraph('<para align="center"><strong>%(description)s</strong></para>' %- {'description': plan.description},- styleSheet["Normal"])- elements.append(P)-- # Filler- P = Paragraph('<para> </para>', styleSheet["Normal"])- elements.append(P)-- # append the table to the document- elements.append(t)-- # Footer, add filler paragraph- P = Paragraph('<para> </para>', styleSheet["Normal"])- elements.append(P)-- # Print date and info- P = Paragraph('<para align="left">%(date)s - %(created)s v%(version)s</para>' %- {'date': _("Created on the <b>%s</b>") %- plan.creation_date.strftime("%d.%m.%Y"),- 'created': "Workout Manager",- 'version': get_version()},- styleSheet["Normal"])- elements.append(P)-- doc.build(elements)-- return response---# ************************-# Meal functions-# ************************--class MealForm(ModelForm):- class Meta:- model = Meal- exclude = ('plan', 'order')---class MealItemForm(ModelForm):- class Meta:- model = MealItem- exclude = ('meal', 'order')---class MealCreateView(YamlFormMixin, CreateView):- '''- Generic view to add a new meal to a nutrition plan- '''-- model = Meal- form_class = MealForm- title = ugettext_lazy('Add new meal')- owner_object = {'pk': 'plan_pk', 'class': NutritionPlan}-- def form_valid(self, form):- plan = get_object_or_404(NutritionPlan, pk=self.kwargs['plan_pk'], user=self.request.user)- form.instance.plan = plan- form.instance.order = 1- return super(MealCreateView, self).form_valid(form)-- def get_success_url(self):- return reverse('wger.nutrition.views.view', kwargs={'id': self.object.plan.id})-- # Send some additional data to the template- def get_context_data(self, **kwargs):- context = super(MealCreateView, self).get_context_data(**kwargs)- context['form_action'] = reverse('meal-add',- kwargs={'plan_pk': self.kwargs['plan_pk']})-- return context---class MealEditView(YamlFormMixin, UpdateView):- '''- Generic view to update an existing meal- '''-- model = Meal- form_class = MealForm- title = ugettext_lazy('Edit meal')- form_action_urlname = 'meal-edit'-- def get_success_url(self):- return reverse('wger.nutrition.views.view', kwargs={'id': self.object.plan.id})---@login_required-def delete_meal(request, id):- '''- Deletes the meal with the given ID- '''-- # Load the meal- meal = get_object_or_404(Meal, pk=id)- plan = meal.plan-- # Only delete if the user is the owner- if plan.user == request.user:- meal.delete()- return HttpResponseRedirect(reverse('wger.nutrition.views.view', kwargs={'id': plan.id}))- else:- return HttpResponseForbidden()---# ************************-# Meal ingredient functions-# ************************-@login_required-def delete_meal_item(request, item_id):- '''- Deletes the meal ingredient with the given ID- '''-- # Load the item- item = get_object_or_404(MealItem, pk=item_id)- plan = item.meal.plan-- # Only delete if the user is the owner- if plan.user == request.user:- item.delete()- return HttpResponseRedirect(reverse('wger.nutrition.views.view', kwargs={'id': plan.id}))- else:- return HttpResponseForbidden()---@login_required-def edit_meal_item(request, id, meal_id, item_id=None):- '''- Form to add a meal to a plan- '''- template_data = {}-- # Load the plan- plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)- template_data['plan'] = plan-- # Load the meal- meal = get_object_or_404(Meal, pk=meal_id)- template_data['meal'] = meal-- if meal.plan != plan:- return HttpResponseForbidden()-- # Load the meal item- # If the object is new, we will receice a 'None' (string) as the ID- # from the template, so we check for it (ValueError) and for an actual- # None (TypeError)- try:- int(item_id)- meal_item = get_object_or_404(MealItem, pk=item_id)- template_data['ingredient'] = meal_item.ingredient.id- template_data['ingredient_searchfield'] = meal_item.ingredient.name-- except ValueError, TypeError:- meal_item = MealItem()-- template_data['meal_item'] = meal_item-- # Check that javascript is activated This is used to hide the drop down list with the- # ingredients and use the autocompleter version instead. This is not only nicer but also much- # faster as the ingredient list from USDA is many thosand entries long.- js_active = request.GET.get('js', False)- template_data['js_active'] = js_active-- # Process request- if request.method == 'POST':- meal_form = MealItemForm(request.POST, instance=meal_item)-- # Pass the ingredient ID back to the template, this is originally set by the JQuery- # autocompleter, in case of errors (max. gramms reached), we need to set the ID manually- # so the user can simply submit again.- template_data['ingredient'] = request.POST.get('ingredient', '')-- template_data['ingredient_searchfield'] = request.POST.get('ingredient_searchfield', '')-- # If the data is valid, save and redirect- if meal_form.is_valid():- meal_item = meal_form.save(commit=False)- meal_item.meal = meal- meal_item.order = 1- meal_item.save()-- return HttpResponseRedirect(reverse('wger.nutrition.views.view', kwargs={'id': id}))-- else:- meal_form = MealItemForm(instance=meal_item)- template_data['form'] = meal_form-- return render_to_response('edit_meal_item.html',- template_data,- context_instance=RequestContext(request))---# ************************-# Ingredient functions-# ************************-def ingredient_overview(request):- '''- Show an overview of all ingredients- '''-- 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']-- return render_to_response('ingredient_overview.html',- template_data,- context_instance=RequestContext(request))---def ingredient_view(request, id, slug=None):- template_data = {}-- ingredient = get_object_or_404(Ingredient, pk=id)- template_data['ingredient'] = ingredient-- return render_to_response('view_ingredient.html',- template_data,- context_instance=RequestContext(request))---class IngredientForm(ModelForm):- class Meta:- model = Ingredient- exclude = ('language',)---class IngredientDeleteView(YamlDeleteMixin, DeleteView):- '''- Generic view to delete an existing ingredient- '''-- model = Ingredient- template_name = 'delete.html'- success_url = reverse_lazy('wger.nutrition.views.ingredient_overview')-- # Send some additional data to the template- def get_context_data(self, **kwargs):- context = super(IngredientDeleteView, self).get_context_data(**kwargs)-- context['title'] = _('Delete %s?') % self.object.name- context['form_action'] = reverse('ingredient-delete', kwargs={'pk': self.kwargs['pk']})-- return context---class IngredientEditView(YamlFormMixin, UpdateView):- '''- Generic view to update an existing ingredient- '''-- model = Ingredient- form_class = IngredientForm- title = ugettext_lazy('Add a new ingredient')- form_action_urlname = 'ingredient-edit'---class IngredientCreateView(YamlFormMixin, CreateView):- '''- Generic view to add a new ingredient- '''-- model = Ingredient- form_class = IngredientForm- title = ugettext_lazy('Add a new ingredient')- form_action = reverse_lazy('ingredient-add')-- def form_valid(self, form):- form.instance.language = load_language()- return super(IngredientCreateView, self).form_valid(form)---def ingredient_search(request):- '''- Search for an exercise, return the result as a JSON list or as HTML page, depending on how- the function was invoked- '''-- # 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)-- # Perform the search- q = request.GET.get('term', '')- ingredients = Ingredient.objects.filter(name__icontains=q, language__in=languages)-- # AJAX-request, this comes from the autocompleter. Create a list and send it back as JSON- if request.is_ajax():-- results = []- for ingredient in ingredients:- ingredient_json = {}- ingredient_json['id'] = ingredient.id- ingredient_json['name'] = ingredient.name- ingredient_json['value'] = ingredient.name- results.append(ingredient_json)- data = json.dumps(results)-- # Return the results to the server- mimetype = 'application/json'- return HttpResponse(data, mimetype)-- # Usual search (perhaps JS disabled), present the results as normal HTML page- else:- template_data = {}- template_data.update(csrf(request))- template_data['ingredients'] = ingredients- template_data['search_term'] = q- return render_to_response('ingredient_search.html',- template_data,- context_instance=RequestContext(request))---# ************************-# Weight units functions-# ************************--class WeightUnitListView(ListView):- '''- Generic view to list all weight units- '''-- model = WeightUnit- template_name = 'units/list.html'- context_object_name = 'unit_list'---class WeightUnitForm(ModelForm):- class Meta:- model = WeightUnit- exclude = ('language',)---class WeightUnitCreateView(YamlFormMixin, CreateView):- '''- Generic view to add a new weight unit for ingredients- '''-- model = WeightUnit- form_class = WeightUnitForm- title = ugettext_lazy('Add a new weight unit')- form_action = reverse_lazy('weight-unit-add')-- def get_success_url(self):- return reverse('weight-unit-list')-- def form_valid(self, form):- form.instance.language = load_language()- return super(WeightUnitCreateView, self).form_valid(form)---class WeightUnitDeleteView(YamlDeleteMixin, DeleteView):- '''- Generic view to delete a weight unit- '''-- model = WeightUnit- success_url = reverse_lazy('weight-unit-list')- title = ugettext_lazy('Delete weight unit?')- form_action_urlname = 'weight-unit-delete'---class WeightUnitUpdateView(YamlFormMixin, UpdateView):- '''- Generic view to update an weight unit- '''-- model = WeightUnit- form_class = WeightUnitForm- title = ugettext_lazy('Edit a weight unit')- form_action_urlname = 'weight-unit-edit'-- def get_success_url(self):- return reverse('weight-unit-list')---# ************************-# Weight units to ingredient functions-# ************************-class WeightUnitIngredientForm(ModelForm):- class Meta:- model = IngredientWeightUnit- exclude = ('ingredient',)---class WeightUnitIngredientCreateView(YamlFormMixin, CreateView):- '''- Generic view to add a new weight unit to ingredient entry- '''-- model = IngredientWeightUnit- form_class = WeightUnitIngredientForm- title = ugettext_lazy('Add a new weight unit')-- # Send some additional data to the template- def get_context_data(self, **kwargs):- context = super(WeightUnitIngredientCreateView, self).get_context_data(**kwargs)- context['form_action'] = reverse('weight-unit-ingredient-add',- kwargs={'ingredient_pk': self.kwargs['ingredient_pk']})- return context-- def get_success_url(self):- return reverse('wger.nutrition.views.ingredient_view',- kwargs={'id': self.kwargs['ingredient_pk']})-- def form_valid(self, form):- ingredient = get_object_or_404(Ingredient, pk=self.kwargs['ingredient_pk'])- form.instance.ingredient = ingredient- return super(WeightUnitIngredientCreateView, self).form_valid(form)---class WeightUnitIngredientUpdateView(YamlFormMixin, UpdateView):- '''- Generic view to update an weight unit to ingredient entry- '''-- model = IngredientWeightUnit- form_class = WeightUnitIngredientForm- title = ugettext_lazy('Edit a weight unit to ingredient connection')- form_action_urlname = 'weight-unit-ingredient-edit'-- def get_success_url(self):- return reverse('wger.nutrition.views.ingredient_view',- kwargs={'id': self.object.ingredient.id})---class WeightUnitIngredientDeleteView(YamlDeleteMixin, DeleteView):- '''- Generic view to delete a weight unit to ingredient entry- '''-- model = IngredientWeightUnit- title = ugettext_lazy('Delete weight unit?')- form_action_urlname = 'weight-unit-ingredient-delete'-- def get_success_url(self):- return reverse('wger.nutrition.views.ingredient_view',- kwargs={'id': self.object.ingredient.id})diff --git a/wger/nutrition/views/__init__.py b/wger/nutrition/views/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/wger/nutrition/views/ingredient.py b/wger/nutrition/views/ingredient.pynew file mode 100644index 000000000..7af295a53--- /dev/null+++ b/wger/nutrition/views/ingredient.py@@ -0,0 +1,285 @@+# -*- 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+import logging+import json++from django.template import RequestContext+from django.shortcuts import render_to_response+from django.shortcuts import get_object_or_404+from django.http import HttpResponse+from django.http import HttpResponseRedirect+from django.http import HttpResponseForbidden+from django.core.context_processors import csrf+from django.core.urlresolvers import reverse+from django.core.urlresolvers import reverse_lazy+from django.contrib.auth.decorators import login_required+from django.forms import ModelForm+from django.utils.translation import ugettext as _+from django.utils.translation import ugettext_lazy+++from django.views.generic import DeleteView+from django.views.generic import CreateView+from django.views.generic import UpdateView+from django.views.generic import ListView+++from wger.nutrition.models import NutritionPlan+from wger.nutrition.models import Meal+from wger.nutrition.models import MealItem+from wger.nutrition.models import Ingredient+from wger.nutrition.models import WeightUnit+from wger.nutrition.models import IngredientWeightUnit++from reportlab.lib.styles import getSampleStyleSheet+from reportlab.lib.pagesizes import A4, cm+from reportlab.platypus import Paragraph, SimpleDocTemplate, Table+from reportlab.lib import colors++from wger.manager.utils import load_language+from wger.manager.utils import load_ingredient_languages++from wger.nutrition.views.meal import MealItemForm++from wger.workout_manager import get_version+from wger.workout_manager.generic_views import YamlFormMixin+from wger.workout_manager.generic_views import YamlDeleteMixin+from wger.workout_manager import helpers+++logger = logging.getLogger('workout_manager.custom')+++# ************************+# Meal ingredient functions+# ************************+@login_required+def delete_meal_item(request, item_id):+ '''+ Deletes the meal ingredient with the given ID+ '''++ # Load the item+ item = get_object_or_404(MealItem, pk=item_id)+ plan = item.meal.plan++ # Only delete if the user is the owner+ if plan.user == request.user:+ item.delete()+ return HttpResponseRedirect(reverse('wger.nutrition.views.plan.view',+ kwargs={'id': plan.id}))+ else:+ return HttpResponseForbidden()+++@login_required+def edit_meal_item(request, id, meal_id, item_id=None):+ '''+ Form to add a meal to a plan+ '''+ template_data = {}++ # Load the plan+ plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)+ template_data['plan'] = plan++ # Load the meal+ meal = get_object_or_404(Meal, pk=meal_id)+ template_data['meal'] = meal++ if meal.plan != plan:+ return HttpResponseForbidden()++ # Load the meal item+ # If the object is new, we will receice a 'None' (string) as the ID+ # from the template, so we check for it (ValueError) and for an actual+ # None (TypeError)+ try:+ int(item_id)+ meal_item = get_object_or_404(MealItem, pk=item_id)+ template_data['ingredient'] = meal_item.ingredient.id+ template_data['ingredient_searchfield'] = meal_item.ingredient.name++ except ValueError, TypeError:+ meal_item = MealItem()++ template_data['meal_item'] = meal_item++ # Check that javascript is activated This is used to hide the drop down list with the+ # ingredients and use the autocompleter version instead. This is not only nicer but also much+ # faster as the ingredient list from USDA is many thosand entries long.+ js_active = request.GET.get('js', False)+ template_data['js_active'] = js_active++ # Process request+ if request.method == 'POST':+ meal_form = MealItemForm(request.POST, instance=meal_item)++ # Pass the ingredient ID back to the template, this is originally set by the JQuery+ # autocompleter, in case of errors (max. gramms reached), we need to set the ID manually+ # so the user can simply submit again.+ template_data['ingredient'] = request.POST.get('ingredient', '')++ template_data['ingredient_searchfield'] = request.POST.get('ingredient_searchfield', '')++ # If the data is valid, save and redirect+ if meal_form.is_valid():+ meal_item = meal_form.save(commit=False)+ meal_item.meal = meal+ meal_item.order = 1+ meal_item.save()++ return HttpResponseRedirect(reverse('wger.nutrition.views.plan.view',+ kwargs={'id': id}))+ #else:+ # logger.debug(meal_form.errors)++ else:+ meal_form = MealItemForm(instance=meal_item)+ template_data['form'] = meal_form++ return render_to_response('edit_meal_item.html',+ template_data,+ context_instance=RequestContext(request))+++# ************************+# Ingredient functions+# ************************+def ingredient_overview(request):+ '''+ Show an overview of all ingredients+ '''++ 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']++ return render_to_response('ingredient_overview.html',+ template_data,+ context_instance=RequestContext(request))+++def ingredient_view(request, id, slug=None):+ template_data = {}++ ingredient = get_object_or_404(Ingredient, pk=id)+ template_data['ingredient'] = ingredient++ return render_to_response('view_ingredient.html',+ template_data,+ context_instance=RequestContext(request))+++class IngredientForm(ModelForm):+ class Meta:+ model = Ingredient+ exclude = ('language',)+++class IngredientDeleteView(YamlDeleteMixin, DeleteView):+ '''+ Generic view to delete an existing ingredient+ '''++ model = Ingredient+ template_name = 'delete.html'+ success_url = reverse_lazy('wger.nutrition.views.ingredient.ingredient_overview')++ # Send some additional data to the template+ def get_context_data(self, **kwargs):+ context = super(IngredientDeleteView, self).get_context_data(**kwargs)++ context['title'] = _('Delete %s?') % self.object.name+ context['form_action'] = reverse('ingredient-delete', kwargs={'pk': self.kwargs['pk']})++ return context+++class IngredientEditView(YamlFormMixin, UpdateView):+ '''+ Generic view to update an existing ingredient+ '''++ model = Ingredient+ form_class = IngredientForm+ title = ugettext_lazy('Add a new ingredient')+ form_action_urlname = 'ingredient-edit'+++class IngredientCreateView(YamlFormMixin, CreateView):+ '''+ Generic view to add a new ingredient+ '''++ model = Ingredient+ form_class = IngredientForm+ title = ugettext_lazy('Add a new ingredient')+ form_action = reverse_lazy('ingredient-add')++ def form_valid(self, form):+ form.instance.language = load_language()+ return super(IngredientCreateView, self).form_valid(form)+++def ingredient_search(request):+ '''+ Search for an exercise, return the result as a JSON list or as HTML page, depending on how+ the function was invoked+ '''++ # 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)++ # Perform the search+ q = request.GET.get('term', '')+ ingredients = Ingredient.objects.filter(name__icontains=q, language__in=languages)++ # AJAX-request, this comes from the autocompleter. Create a list and send it back as JSON+ if request.is_ajax():++ results = []+ for ingredient in ingredients:+ ingredient_json = {}+ ingredient_json['id'] = ingredient.id+ ingredient_json['name'] = ingredient.name+ ingredient_json['value'] = ingredient.name+ results.append(ingredient_json)+ data = json.dumps(results)++ # Return the results to the server+ mimetype = 'application/json'+ return HttpResponse(data, mimetype)++ # Usual search (perhaps JS disabled), present the results as normal HTML page+ else:+ template_data = {}+ template_data.update(csrf(request))+ template_data['ingredients'] = ingredients+ template_data['search_term'] = q+ return render_to_response('ingredient_search.html',+ template_data,+ context_instance=RequestContext(request))diff --git a/wger/nutrition/views/meal.py b/wger/nutrition/views/meal.pynew file mode 100644index 000000000..fcd78d6d5--- /dev/null+++ b/wger/nutrition/views/meal.py@@ -0,0 +1,113 @@+# -*- 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+import logging++from django.shortcuts import get_object_or_404+from django.http import HttpResponseRedirect+from django.http import HttpResponseForbidden+from django.core.urlresolvers import reverse+from django.contrib.auth.decorators import login_required+from django.forms import ModelForm+from django.utils.translation import ugettext_lazy++from django.views.generic import CreateView+from django.views.generic import UpdateView++from wger.nutrition.models import NutritionPlan+from wger.nutrition.models import Meal+from wger.nutrition.models import MealItem++from wger.workout_manager.generic_views import YamlFormMixin+++logger = logging.getLogger('workout_manager.custom')+++# ************************+# Meal functions+# ************************++class MealForm(ModelForm):+ class Meta:+ model = Meal+ exclude = ('plan', 'order')+++class MealItemForm(ModelForm):+ class Meta:+ model = MealItem+ exclude = ('meal', 'order')+++class MealCreateView(YamlFormMixin, CreateView):+ '''+ Generic view to add a new meal to a nutrition plan+ '''++ model = Meal+ form_class = MealForm+ title = ugettext_lazy('Add new meal')+ owner_object = {'pk': 'plan_pk', 'class': NutritionPlan}++ def form_valid(self, form):+ plan = get_object_or_404(NutritionPlan, pk=self.kwargs['plan_pk'], user=self.request.user)+ form.instance.plan = plan+ form.instance.order = 1+ return super(MealCreateView, self).form_valid(form)++ def get_success_url(self):+ return reverse('wger.nutrition.views.plan.view', kwargs={'id': self.object.plan.id})++ # Send some additional data to the template+ def get_context_data(self, **kwargs):+ context = super(MealCreateView, self).get_context_data(**kwargs)+ context['form_action'] = reverse('meal-add',+ kwargs={'plan_pk': self.kwargs['plan_pk']})++ return context+++class MealEditView(YamlFormMixin, UpdateView):+ '''+ Generic view to update an existing meal+ '''++ model = Meal+ form_class = MealForm+ title = ugettext_lazy('Edit meal')+ form_action_urlname = 'meal-edit'++ def get_success_url(self):+ return reverse('wger.nutrition.views.plan.view', kwargs={'id': self.object.plan.id})+++@login_required+def delete_meal(request, id):+ '''+ Deletes the meal with the given ID+ '''++ # Load the meal+ meal = get_object_or_404(Meal, pk=id)+ plan = meal.plan++ # Only delete if the user is the owner+ if plan.user == request.user:+ meal.delete()+ return HttpResponseRedirect(reverse('wger.nutrition.views.plan.view',+ kwargs={'id': plan.id}))+ else:+ return HttpResponseForbidden()diff --git a/wger/nutrition/views/meal_ingredient.py b/wger/nutrition/views/meal_ingredient.pynew file mode 100644index 000000000..a233bb555--- /dev/null+++ b/wger/nutrition/views/meal_ingredient.py@@ -0,0 +1,122 @@+# -*- 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+import logging++from django.template import RequestContext+from django.shortcuts import render_to_response+from django.shortcuts import get_object_or_404+from django.http import HttpResponseRedirect+from django.http import HttpResponseForbidden+from django.core.urlresolvers import reverse+from django.contrib.auth.decorators import login_required++from wger.nutrition.models import NutritionPlan+from wger.nutrition.models import Meal+from wger.nutrition.models import MealItem+++logger = logging.getLogger('workout_manager.custom')+++# ************************+# Meal ingredient functions+# ************************+@login_required+def delete_meal_item(request, item_id):+ '''+ Deletes the meal ingredient with the given ID+ '''++ # Load the item+ item = get_object_or_404(MealItem, pk=item_id)+ plan = item.meal.plan++ # Only delete if the user is the owner+ if plan.user == request.user:+ item.delete()+ return HttpResponseRedirect(reverse('wger.nutrition.views.plan.view',+ kwargs={'id': plan.id}))+ else:+ return HttpResponseForbidden()+++@login_required+def edit_meal_item(request, id, meal_id, item_id=None):+ '''+ Form to add a meal to a plan+ '''+ template_data = {}++ # Load the plan+ plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)+ template_data['plan'] = plan++ # Load the meal+ meal = get_object_or_404(Meal, pk=meal_id)+ template_data['meal'] = meal++ if meal.plan != plan:+ return HttpResponseForbidden()++ # Load the meal item+ # If the object is new, we will receice a 'None' (string) as the ID+ # from the template, so we check for it (ValueError) and for an actual+ # None (TypeError)+ try:+ int(item_id)+ meal_item = get_object_or_404(MealItem, pk=item_id)+ template_data['ingredient'] = meal_item.ingredient.id+ template_data['ingredient_searchfield'] = meal_item.ingredient.name++ except ValueError, TypeError:+ meal_item = MealItem()++ #template_data['meal_item'] = meal_item++ # Check that javascript is activated This is used to hide the drop down list with the+ # ingredients and use the autocompleter version instead. This is not only nicer but also much+ # faster as the ingredient list from USDA is many thosand entries long.+ js_active = request.GET.get('js', False)+ template_data['js_active'] = js_active++ # Process request+ if request.method == 'POST':+ meal_form = MealItemForm(request.POST, instance=meal_item)++ # Pass the ingredient ID back to the template, this is originally set by the JQuery+ # autocompleter, in case of errors (max. gramms reached), we need to set the ID manually+ # so the user can simply submit again.+ template_data['ingredient'] = request.POST.get('ingredient', '')++ template_data['ingredient_searchfield'] = request.POST.get('ingredient_searchfield', '')++ # If the data is valid, save and redirect+ if meal_form.is_valid():+ meal_item = meal_form.save(commit=False)+ meal_item.meal = meal+ meal_item.order = 1+ meal_item.save()++ return HttpResponseRedirect(reverse('wger.nutrition.views.plan.view',+ kwargs={'id': id}))++ else:+ meal_form = MealItemForm(instance=meal_item)+ template_data['form'] = meal_form++ return render_to_response('edit_meal_item.html',+ template_data,+ context_instance=RequestContext(request))diff --git a/wger/nutrition/views/plan.py b/wger/nutrition/views/plan.pynew file mode 100644index 000000000..edd1b74d9--- /dev/null+++ b/wger/nutrition/views/plan.py@@ -0,0 +1,287 @@+# -*- 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+import logging++from django.template import RequestContext+from django.shortcuts import render_to_response+from django.shortcuts import get_object_or_404+from django.http import HttpResponse+from django.http import HttpResponseRedirect+from django.core.context_processors import csrf+from django.core.urlresolvers import reverse+from django.core.urlresolvers import reverse_lazy+from django.contrib.auth.decorators import login_required+from django.forms import ModelForm+from django.utils.translation import ugettext as _+from django.utils.translation import ugettext_lazy++from django.views.generic import DeleteView+from django.views.generic import UpdateView++from wger.nutrition.models import NutritionPlan++from reportlab.lib.styles import getSampleStyleSheet+from reportlab.lib.pagesizes import A4, cm+from reportlab.platypus import Paragraph, SimpleDocTemplate, Table+from reportlab.lib import colors++from wger.manager.utils import load_language++from wger.workout_manager import get_version+from wger.workout_manager.generic_views import YamlFormMixin+from wger.workout_manager.generic_views import YamlDeleteMixin+++logger = logging.getLogger('workout_manager.custom')+++# ************************+# Plan functions+# ************************++class PlanForm(ModelForm):+ class Meta:+ model = NutritionPlan+ exclude = ('user', 'language', )+++@login_required+def overview(request):+ template_data = {}+ template_data.update(csrf(request))++ plans = NutritionPlan.objects.filter(user=request.user)+ template_data['plans'] = plans++ return render_to_response('nutrition_overview.html',+ template_data,+ context_instance=RequestContext(request))+++@login_required+def add(request):+ '''+ Add a new nutrition plan and redirect to its page+ '''++ plan = NutritionPlan()+ plan.user = request.user+ plan.language = load_language()+ plan.save()++ return HttpResponseRedirect(reverse('wger.nutrition.views.plan.view', kwargs={'id': plan.id}))+++class PlanDeleteView(YamlDeleteMixin, DeleteView):+ '''+ Generic view to delete a nutritional plan+ '''++ model = NutritionPlan+ success_url = reverse_lazy('wger.nutrition.views.plan.overview')+ title = ugettext_lazy('Delete nutritional plan?')+ form_action_urlname = 'nutrition-delete'+++class PlanEditView(YamlFormMixin, UpdateView):+ '''+ Generic view to update an existing nutritional plan+ '''++ model = NutritionPlan+ form_class = PlanForm+ title = ugettext_lazy('Add a new nutritional plan')+ form_action_urlname = 'nutrition-edit'+++@login_required+def view(request, id):+ '''+ Show the nutrition plan with the given ID+ '''+ template_data = {}++ plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)+ template_data['plan'] = plan++ # Load the language and pass it to the template+ language = load_language()+ template_data['language'] = language++ # Get the nutrional info++ template_data['nutritional_data'] = plan.get_nutritional_values()++ return render_to_response('view_nutrition_plan.html',+ template_data,+ context_instance=RequestContext(request))+++@login_required+def copy(request, pk):+ '''+ Copy the nutrition plan+ '''++ plan = get_object_or_404(NutritionPlan, pk=pk, user=request.user)++ # Copy plan+ meals = plan.meal_set.all()++ plan_copy = plan+ plan_copy.pk = None+ plan_copy.save()++ # Copy the meals+ for meal in meals:+ meal_items = meal.mealitem_set.all()++ meal_copy = meal+ meal_copy.pk = None+ meal_copy.plan = plan_copy+ meal_copy.save()++ # Copy the individual meal entries+ for item in meal_items:+ item_copy = item+ item_copy.pk = None+ item_copy.meal = meal_copy+ item.save()++ # Redirect+ return HttpResponseRedirect(reverse('wger.nutrition.views.plan.view', kwargs={'id': plan.id}))+++@login_required+def export_pdf(request, id):+ '''+ Generates a PDF with the contents of a nutrition plan++ See also+ * http://www.blog.pythonlibrary.org/2010/09/21/reportlab+ * http://www.reportlab.com/apis/reportlab/dev/platypus.html+ '''++ #Load the workout+ plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)++ # Create the HttpResponse object with the appropriate PDF headers.+ response = HttpResponse(mimetype='application/pdf')++ # Translators: translation can only have ASCII characters+ response['Content-Disposition'] = 'attachment; filename=%s.pdf' % _('nutritional-plan')++ # Create the PDF object, using the response object as its "file."+ doc = SimpleDocTemplate(response,+ pagesize=A4,+ title=_('Workout'),+ author=_('Workout Manager'),+ subject=_('Nutritional plan %s') % request.user.username)++ # Background colour for header+ # Reportlab doesn't use the HTML hexadecimal format, but has a range of+ # 0 till 1, so we have to convert here.+ header_colour = colors.Color(int('73', 16) / 255.0,+ int('8a', 16) / 255.0,+ int('5f', 16) / 255.0)++ # container for the 'Flowable' objects+ elements = []++ styleSheet = getSampleStyleSheet()+ data = []++ # Iterate through the Plan+ meal_markers = []+ ingredient_markers = []++ # Meals+ i = 0+ for meal in plan.meal_set.select_related():+ i += 1++ meal_markers.append(len(data))++ if not meal.time:+ P = Paragraph('<para align="center"><strong>%(meal_nr)s</strong></para>' %+ {'meal_nr': i},+ styleSheet["Normal"])+ else:+ P = Paragraph('<para align="center"><strong>%(meal_nr)s - '+ '%(meal_time)s</strong></para>' %+ {'meal_nr': i,+ 'meal_time': meal.time.strftime("%H:%M")},+ styleSheet["Normal"])+ data.append([P])++ # Ingredients+ for item in meal.mealitem_set.select_related():+ ingredient_markers.append(len(data))++ P = Paragraph('<para>%s</para>' % item.ingredient.name,+ styleSheet["Normal"])+ data.append(["%sg" % item.amount_gramm, P])++ # Set general table styles++ #('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),+ #('BOX', (0,0), (-1,-1), 0.25, colors.black)+ table_style = []++ # Set specific styles, e.g. background for title cells+ for marker in meal_markers:+ # Set background colour for headings+ table_style.append(('BACKGROUND', (0, marker), (-1, marker), header_colour))+ table_style.append(('BOX', (0, marker), (-1, marker), 1.25, colors.black))++ # Make the headings span the whole width+ table_style.append(('SPAN', (0, marker), (-1, marker)))++ t = Table(data, style=table_style)++ # Manually set the width of the columns+ t._argW[0] = 2 * cm++ # Set the title (if available)+ if plan.description:+ P = Paragraph('<para align="center"><strong>%(description)s</strong></para>' %+ {'description': plan.description},+ styleSheet["Normal"])+ elements.append(P)++ # Filler+ P = Paragraph('<para> </para>', styleSheet["Normal"])+ elements.append(P)++ # append the table to the document+ elements.append(t)++ # Footer, add filler paragraph+ P = Paragraph('<para> </para>', styleSheet["Normal"])+ elements.append(P)++ # Print date and info+ P = Paragraph('<para align="left">%(date)s - %(created)s v%(version)s</para>' %+ {'date': _("Created on the <b>%s</b>") %+ plan.creation_date.strftime("%d.%m.%Y"),+ 'created': "Workout Manager",+ 'version': get_version()},+ styleSheet["Normal"])+ elements.append(P)++ doc.build(elements)++ return responsediff --git a/wger/nutrition/views/unit.py b/wger/nutrition/views/unit.pynew file mode 100644index 000000000..305728144--- /dev/null+++ b/wger/nutrition/views/unit.py@@ -0,0 +1,99 @@+# -*- 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+import logging++from django.core.urlresolvers import reverse+from django.core.urlresolvers import reverse_lazy+from django.forms import ModelForm+from django.utils.translation import ugettext_lazy+++from django.views.generic import DeleteView+from django.views.generic import CreateView+from django.views.generic import UpdateView+from django.views.generic import ListView++from wger.nutrition.models import WeightUnit++from wger.manager.utils import load_language++from wger.workout_manager.generic_views import YamlFormMixin+from wger.workout_manager.generic_views import YamlDeleteMixin+++logger = logging.getLogger('workout_manager.custom')+# ************************+# Weight units functions+# ************************+++class WeightUnitListView(ListView):+ '''+ Generic view to list all weight units+ '''++ model = WeightUnit+ template_name = 'units/list.html'+ context_object_name = 'unit_list'+++class WeightUnitForm(ModelForm):+ class Meta:+ model = WeightUnit+ exclude = ('language',)+++class WeightUnitCreateView(YamlFormMixin, CreateView):+ '''+ Generic view to add a new weight unit for ingredients+ '''++ model = WeightUnit+ form_class = WeightUnitForm+ title = ugettext_lazy('Add a new weight unit')+ form_action = reverse_lazy('weight-unit-add')++ def get_success_url(self):+ return reverse('weight-unit-list')++ def form_valid(self, form):+ form.instance.language = load_language()+ return super(WeightUnitCreateView, self).form_valid(form)+++class WeightUnitDeleteView(YamlDeleteMixin, DeleteView):+ '''+ Generic view to delete a weight unit+ '''++ model = WeightUnit+ success_url = reverse_lazy('weight-unit-list')+ title = ugettext_lazy('Delete weight unit?')+ form_action_urlname = 'weight-unit-delete'+++class WeightUnitUpdateView(YamlFormMixin, UpdateView):+ '''+ Generic view to update an weight unit+ '''++ model = WeightUnit+ form_class = WeightUnitForm+ title = ugettext_lazy('Edit a weight unit')+ form_action_urlname = 'weight-unit-edit'++ def get_success_url(self):+ return reverse('weight-unit-list')diff --git a/wger/nutrition/views/unit_ingredient.py b/wger/nutrition/views/unit_ingredient.pynew file mode 100644index 000000000..7d3d9125d--- /dev/null+++ b/wger/nutrition/views/unit_ingredient.py@@ -0,0 +1,98 @@+# -*- 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+import logging++from django.shortcuts import get_object_or_404+from django.core.urlresolvers import reverse+from django.forms import ModelForm+from django.utils.translation import ugettext_lazy++from django.views.generic import DeleteView+from django.views.generic import CreateView+from django.views.generic import UpdateView++from wger.nutrition.models import Ingredient+from wger.nutrition.models import IngredientWeightUnit++from wger.workout_manager.generic_views import YamlFormMixin+from wger.workout_manager.generic_views import YamlDeleteMixin+++logger = logging.getLogger('workout_manager.custom')+++# ************************+# Weight units to ingredient functions+# ************************+class WeightUnitIngredientForm(ModelForm):+ class Meta:+ model = IngredientWeightUnit+ exclude = ('ingredient',)+++class WeightUnitIngredientCreateView(YamlFormMixin, CreateView):+ '''+ Generic view to add a new weight unit to ingredient entry+ '''++ model = IngredientWeightUnit+ form_class = WeightUnitIngredientForm+ title = ugettext_lazy('Add a new weight unit')++ # Send some additional data to the template+ def get_context_data(self, **kwargs):+ context = super(WeightUnitIngredientCreateView, self).get_context_data(**kwargs)+ context['form_action'] = reverse('weight-unit-ingredient-add',+ kwargs={'ingredient_pk': self.kwargs['ingredient_pk']})+ return context++ def get_success_url(self):+ return reverse('wger.nutrition.views.ingredient.ingredient_view',+ kwargs={'id': self.kwargs['ingredient_pk']})++ def form_valid(self, form):+ ingredient = get_object_or_404(Ingredient, pk=self.kwargs['ingredient_pk'])+ form.instance.ingredient = ingredient+ return super(WeightUnitIngredientCreateView, self).form_valid(form)+++class WeightUnitIngredientUpdateView(YamlFormMixin, UpdateView):+ '''+ Generic view to update an weight unit to ingredient entry+ '''++ model = IngredientWeightUnit+ form_class = WeightUnitIngredientForm+ title = ugettext_lazy('Edit a weight unit to ingredient connection')+ form_action_urlname = 'weight-unit-ingredient-edit'++ def get_success_url(self):+ return reverse('wger.nutrition.views.ingredient.ingredient_view',+ kwargs={'id': self.object.ingredient.id})+++class WeightUnitIngredientDeleteView(YamlDeleteMixin, DeleteView):+ '''+ Generic view to delete a weight unit to ingredient entry+ '''++ model = IngredientWeightUnit+ title = ugettext_lazy('Delete weight unit?')+ form_action_urlname = 'weight-unit-ingredient-delete'++ def get_success_url(self):+ return reverse('wger.nutrition.views.ingredient.ingredient_view',+ kwargs={'id': self.object.ingredient.id})