Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add views and tests to add weight units to ingredients
Roland Geiderf9acd0b717de
diff --git a/wger/manager/tests/testcase.py b/wger/manager/tests/testcase.pyindex 7334f7957..35e7a611e 100644--- a/wger/manager/tests/testcase.py+++ b/wger/manager/tests/testcase.py@@ -13,6 +13,7 @@# You should have received a copy of the GNU Affero General Public Licenseimport os+import decimalfrom django.core.urlresolvers import reversefrom django.core.urlresolvers import NoReverseMatch@@ -56,6 +57,27 @@ class WorkoutManagerTestCase(TestCase):'''self.client.logout()+ def compare_fields(self, field, value):+ current_field_class = field.__class__.__name__++ # Standard types, simply compare+ if current_field_class in ('unicode', 'int', 'float', 'time'):+ self.assertEqual(field, value)++ # decimal, convert+ if current_field_class == 'Decimal':+ self.assertEqual(field, decimal.Decimal(unicode(value)))++ # Related manager, iterate+ elif current_field_class == 'ManyRelatedManager':+ for j in field.all():+ self.assertIn(j.id, value)++ # Other objects (from foreign keys), ignore+ else:+ pass+ #print "Don't know how to check for {0}!".format(current_field_class)+class WorkoutManagerDeleteTestCase(WorkoutManagerTestCase):'''@@ -185,13 +207,11 @@ class WorkoutManagerEditTestCase(WorkoutManagerTestCase):else:self.assertEqual(response.status_code, 302)++ # Check that the data is correctfor i in self.data:current_field = getattr(entry_after, i)- if current_field.__class__.__name__ == 'ManyRelatedManager':- for j in current_field.all():- self.assertIn(j.id, self.data[i])- else:- self.assertEqual(current_field, self.data[i])+ self.compare_fields(current_field, self.data[i])def test_edit_object_anonymous(self):'''@@ -276,13 +296,11 @@ class WorkoutManagerAddTestCase(WorkoutManagerTestCase):else:self.assertEqual(response.status_code, 302)entry = self.object_class.objects.get(pk=self.pk)++ # Check that the data is correctfor i in self.data:current_field = getattr(entry, i)- if current_field.__class__.__name__ == 'ManyRelatedManager':- for j in current_field.all():- self.assertIn(j.id, self.data[i])- else:- self.assertEqual(current_field, self.data[i])+ self.compare_fields(current_field, self.data[i])self.assertEqual(count_before + 1, count_after)diff --git a/wger/nutrition/fixtures/test-ingredients.json b/wger/nutrition/fixtures/test-ingredients.jsonindex 6e09b44ce..fddab02aa 100644--- a/wger/nutrition/fixtures/test-ingredients.json+++ b/wger/nutrition/fixtures/test-ingredients.json@@ -94,5 +94,35 @@"protein": 10,"carbohydrates": 5.0}- }+ },+ {+ "pk": 1,+ "model": "nutrition.ingredientweightunit",+ "fields": {+ "amount": "1",+ "gramm": 109,+ "unit": 4,+ "ingredient": 1+ }+ },+ {+ "pk": 2,+ "model": "nutrition.ingredientweightunit",+ "fields": {+ "amount": "0.5",+ "gramm": 223,+ "unit": 5,+ "ingredient": 1+ }+ },+ {+ "pk": 3,+ "model": "nutrition.ingredientweightunit",+ "fields": {+ "amount": "1",+ "gramm": 12,+ "unit": 6,+ "ingredient": 1+ }+ }]diff --git a/wger/nutrition/models.py b/wger/nutrition/models.pyindex 199c4d8cd..b088f3469 100644--- a/wger/nutrition/models.py+++ b/wger/nutrition/models.py@@ -209,9 +209,16 @@ class IngredientWeightUnit(models.Model):gramm = models.IntegerField(verbose_name=_('Amount in gramms'))amount = models.DecimalField(decimal_places=2,max_digits=5,+ default=1,verbose_name=_('Amount'),help_text=_('Unit amount, e.g. "1 Cup" or "1/2 spoon"'))+ def get_owner_object(self):+ '''+ Weight unit has no owner information+ '''+ return None+def __unicode__(self):'''Return a more human-readable representationdiff --git a/wger/nutrition/templates/view_ingredient.html b/wger/nutrition/templates/view_ingredient.htmlindex 84702e81b..146885261 100644--- a/wger/nutrition/templates/view_ingredient.html+++ b/wger/nutrition/templates/view_ingredient.html@@ -102,6 +102,57 @@{% trans 'Edit ingredient' %}</a></p>++<h3>{% trans "Weight units" %}</h3>+<p>+<a href="{% url 'weight-unit-ingredient-add' ingredient.id %}"+ class="modal-dialog">+ <img src="{% static 'images/icons/new.svg' %}"+ width="32"+ height="32"+ alt="{% trans 'Add new weight unit' %}"+ title="{% trans 'Add new weight unit' %}">+{% trans "Add new weight unit" %}+</a>+</p>+{% if ingredient.ingredientweightunit_set.all %}+ <table>+ <thead>+ <tr>+ <th>{% trans "Name (values are approximate)" %}</th>+ </tr>+ </thead>+ <tbody>+ {% for unit in ingredient.ingredientweightunit_set.all %}+ <tr>+ <td>+ {{unit.amount}} {{unit.unit.name}} = {{unit.gramm}}g+ <span class="editoptions float-right">+ <a href="{% url 'weight-unit-ingredient-edit' unit.id %}"+ title="{% trans 'Edit' %}"+ class="modal-dialog">+ <img src="{% static 'images/icons/edit.svg' %}"+ width="16"+ height="16"+ alt="{% trans 'Edit' %}"+ title="{% trans 'Edit' %}">+ </a>+ <a href="{% url 'weight-unit-ingredient-delete' unit.id %}"+ title="{% trans 'Delete' %}"+ class="modal-dialog">+ <img src="{% static 'images/icons/trash.svg' %}"+ width="16"+ height="16"+ alt="{% trans 'Delete' %}"+ title="{% trans 'Delete' %}">+ </a>+ </span>+ </td>+ </tr>+ {% endfor %}+ </tbody>+ </table>+{% endif %}{% endif %}{% cc_by_sa_sidebar language %}diff --git a/wger/nutrition/tests/__init__.py b/wger/nutrition/tests/__init__.pyindex 794fa2180..fed748843 100644--- a/wger/nutrition/tests/__init__.py+++ b/wger/nutrition/tests/__init__.py@@ -6,3 +6,4 @@ from wger.nutrition.tests.ingredient import *from wger.nutrition.tests.ingredient_overview import *from wger.nutrition.tests.meal import *from wger.nutrition.tests.weight_unit import *+from wger.nutrition.tests.weight_unit_ingredient import *diff --git a/wger/nutrition/tests/weight_unit_ingredient.py b/wger/nutrition/tests/weight_unit_ingredient.pynew file mode 100644index 000000000..dd2a4c086--- /dev/null+++ b/wger/nutrition/tests/weight_unit_ingredient.py@@ -0,0 +1,59 @@+# 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+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.++from django.core.urlresolvers import reverse_lazy++from wger.nutrition.models import IngredientWeightUnit++from wger.manager.tests.testcase import WorkoutManagerDeleteTestCase+from wger.manager.tests.testcase import WorkoutManagerEditTestCase+from wger.manager.tests.testcase import WorkoutManagerAddTestCase+++class AddWeightUnitIngredientTestCase(WorkoutManagerAddTestCase):+ '''+ Tests adding a new weight unit to an ingredient+ '''++ object_class = IngredientWeightUnit+ url = reverse_lazy('weight-unit-ingredient-add',+ kwargs={'ingredient_pk': 1})+ data = {'unit': 1,+ 'gramm': 123,+ 'amount': 1}+ pk = 4+++class DeleteWeightUnitIngredientTestCase(WorkoutManagerDeleteTestCase):+ '''+ Tests deleting a weight unit from an ingredient+ '''++ object_class = IngredientWeightUnit+ url = 'weight-unit-ingredient-delete'+ pk = 1+++class EditWeightUnitTestCase(WorkoutManagerEditTestCase):+ '''+ Tests editing a weight unit from an ingredient+ '''++ object_class = IngredientWeightUnit+ url = 'weight-unit-ingredient-edit'+ pk = 1+ data = {'unit': 1,+ 'gramm': 10,+ 'amount': 0.3}diff --git a/wger/nutrition/urls.py b/wger/nutrition/urls.pyindex a3561588a..cd5b05e88 100644--- a/wger/nutrition/urls.py+++ b/wger/nutrition/urls.py@@ -15,6 +15,10 @@ from wger.nutrition.views import WeightUnitCreateViewfrom wger.nutrition.views import WeightUnitDeleteViewfrom wger.nutrition.views import WeightUnitUpdateView+from wger.nutrition.views import WeightUnitIngredientCreateView+from wger.nutrition.views import WeightUnitIngredientUpdateView+from wger.nutrition.views import WeightUnitIngredientDeleteView+urlpatterns = patterns('wger.nutrition.views',url(r'^overview/$', 'overview'),@@ -82,7 +86,13 @@ urlpatterns = patterns('wger.nutrition.views',# Ingredient to weight units cross table- #url(r'^ingredient/unit/add-to-ingredient/$',- # permission_required('exercises.change_exercise')(WeightUnitCreateView.as_view()),- # name='weight-unit-add'),+ url(r'^ingredient/(?P<ingredient_pk>\d+)/unit/add/$',+ permission_required('exercises.change_exercise')(WeightUnitIngredientCreateView.as_view()),+ name='weight-unit-ingredient-add'),+ url(r'^ingredient/unit-to-ingredient/(?P<pk>\d+)/edit/$',+ permission_required('exercises.change_exercise')(WeightUnitIngredientUpdateView.as_view()),+ name='weight-unit-ingredient-edit'),+ url(r'^ingredient/unit-to-ingredient/(?P<pk>\d+)/delete/$',+ permission_required('exercises.change_exercise')(WeightUnitIngredientDeleteView.as_view()),+ name='weight-unit-ingredient-delete'),)diff --git a/wger/nutrition/views.py b/wger/nutrition/views.pyindex 4055f7b8b..02e51391d 100644--- a/wger/nutrition/views.py+++ b/wger/nutrition/views.py@@ -42,6 +42,7 @@ from wger.nutrition.models import Mealfrom wger.nutrition.models import MealItemfrom wger.nutrition.models import Ingredientfrom wger.nutrition.models import WeightUnit+from wger.nutrition.models import IngredientWeightUnitfrom reportlab.lib.styles import getSampleStyleSheetfrom reportlab.lib.pagesizes import A4, cm@@ -594,7 +595,7 @@ def ingredient_search(request):# ************************-# Ingredient units functions+# Weight units functions# ************************class WeightUnitListView(ListView):@@ -654,3 +655,67 @@ class WeightUnitUpdateView(YamlFormMixin, UpdateView):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})