Self hosted FLOSS fitness/workout, nutrition and weight tracker
Simplify the way the units are handled for nutritional plans
Roland Geider1f6c32549cf2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 22646a247..7d265b666 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,3 +18,8 @@ timer or similar. The `setting-repetitionunit` endpoint now exposes the new fiel<https://github.com/wger-project/wger/issues/2124>Automatically read the date from uploaded image to the gallery.++Improve serving size support for ingredients. Users can now log food in+everyday units like "1 Serving (2 biscuits)" or "1 Cup" instead of only grams,+with serving sizes automatically imported from Open Food Facts.+The `/api/v2/weightunit/` endpoint has been removed.diff --git a/wger/core/fixtures/groups.json b/wger/core/fixtures/groups.jsonindex 53a22fffc..3a9483c60 100644--- a/wger/core/fixtures/groups.json+++ b/wger/core/fixtures/groups.json@@ -273,21 +273,6 @@"nutrition","ingredientweightunit"],- [- "add_weightunit",- "nutrition",- "weightunit"- ],- [- "change_weightunit",- "nutrition",- "weightunit"- ],- [- "delete_weightunit",- "nutrition",- "weightunit"- ],["add_trophy","trophies",diff --git a/wger/core/templates/navigation.html b/wger/core/templates/navigation.htmlindex 56499198e..5a84d7c09 100644--- a/wger/core/templates/navigation.html+++ b/wger/core/templates/navigation.html@@ -178,16 +178,6 @@{% translate "Ingredient overview" %}</a></li>- {% if perms.nutrition %}- <li class="dropdown-divider"></li>- <li class="dropdown-header">{% translate "Administration" %}</li>- <li>- <a class="dropdown-item"- href="{% url 'nutrition:weight_unit:list' %}">- {% translate "Ingredient weight units" %}- </a>- </li>- {% endif %}</ul></li>diff --git a/wger/core/tests/base_testcase.py b/wger/core/tests/base_testcase.pyindex 343625224..d583f96e7 100644--- a/wger/core/tests/base_testcase.py+++ b/wger/core/tests/base_testcase.py@@ -124,7 +124,6 @@ class BaseTestCase:'test-muscles','test-exercises','test-exercise-images',- 'test-weight-units','test-ingredients','test-nutrition-data','test-nutrition-diary',diff --git a/wger/nutrition/api/serializers.py b/wger/nutrition/api/serializers.pyindex 7ef34af1a..14f81cabb 100644--- a/wger/nutrition/api/serializers.py+++ b/wger/nutrition/api/serializers.py@@ -29,7 +29,6 @@ from wger.nutrition.models import (Meal,MealItem,NutritionPlan,- WeightUnit,)@@ -38,17 +37,13 @@ class IngredientWeightUnitSerializer(serializers.ModelSerializer):IngredientWeightUnit serializer"""- unit_name = serializers.CharField(source='unit.name', read_only=True)-class Meta:model = IngredientWeightUnitfields = ('id',- 'amount','gram','ingredient',- 'unit',- 'unit_name',+ 'name',)@@ -57,30 +52,11 @@ class IngredientWeightUnitInfoSerializer(serializers.ModelSerializer):IngredientWeightUnit info serializer"""- unit_name = serializers.CharField(source='unit.name', read_only=True)-class Meta:model = IngredientWeightUnit- depth = 1fields = ('id','gram',- 'amount',- 'unit',- 'unit_name',- )---class WeightUnitSerializer(serializers.ModelSerializer):- """- WeightUnit serializer- """-- class Meta:- model = WeightUnit- fields = (- 'id',- 'language','name',)diff --git a/wger/nutrition/api/views.py b/wger/nutrition/api/views.pyindex 7b7028dc9..b3eae8395 100644--- a/wger/nutrition/api/views.py+++ b/wger/nutrition/api/views.py@@ -50,7 +50,6 @@ from wger.nutrition.api.serializers import (NutritionalValuesSerializer,NutritionPlanInfoSerializer,NutritionPlanSerializer,- WeightUnitSerializer,)from wger.nutrition.forms import UnitChooserFormfrom wger.nutrition.models import (@@ -61,7 +60,6 @@ from wger.nutrition.models import (Meal,MealItem,NutritionPlan,- WeightUnit,)from wger.utils.constants import (ENGLISH_SHORT_NAME,@@ -87,7 +85,7 @@ class IngredientViewSet(viewsets.ReadOnlyModelViewSet):queryset = Ingredient.objects.select_related('language','license',- ).prefetch_related('ingredientweightunit_set__unit')+ ).prefetch_related('ingredientweightunit_set')@method_decorator(cache_page(settings.WGER_SETTINGS['INGREDIENT_CACHE_TTL']))def list(self, request, *args, **kwargs):@@ -175,30 +173,18 @@ class ImageViewSet(viewsets.ReadOnlyModelViewSet):return Image.objects.select_related('ingredient')-class WeightUnitViewSet(viewsets.ReadOnlyModelViewSet):- """- API endpoint for weight unit objects- """-- queryset = WeightUnit.objects.all()- serializer_class = WeightUnitSerializer- ordering_fields = '__all__'- filterset_fields = ('language', 'name')--class IngredientWeightUnitViewSet(viewsets.ReadOnlyModelViewSet):"""- API endpoint for many-to-many table ingredient-weight unit objects+ API endpoint for ingredient weight unit objects"""queryset = IngredientWeightUnit.objects.all()serializer_class = IngredientWeightUnitSerializerordering_fields = '__all__'filterset_fields = (- 'amount','gram','ingredient',- 'unit',+ 'name',)diff --git a/wger/nutrition/consts.py b/wger/nutrition/consts.pyindex d5c4f2d95..375196364 100644--- a/wger/nutrition/consts.py+++ b/wger/nutrition/consts.py@@ -14,9 +14,6 @@# You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.-MEALITEM_WEIGHT_GRAM = '1'-MEALITEM_WEIGHT_UNIT = '2'-ENERGY_FACTOR = {'protein': {'kg': 4, 'lb': 113},'carbohydrates': {'kg': 4, 'lb': 113},diff --git a/wger/nutrition/extract_info/off.py b/wger/nutrition/extract_info/off.pyindex cd4cfa4dd..f5e0ea9ab 100644--- a/wger/nutrition/extract_info/off.py+++ b/wger/nutrition/extract_info/off.py@@ -16,6 +16,10 @@# Standard Libraryimport re+# Django+from django.utils import translation+from django.utils.translation import gettext+# wgerfrom wger.nutrition.consts import KJ_PER_KCALfrom wger.nutrition.dataclasses import IngredientData@@ -55,13 +59,17 @@ def _mass_match_to_gram(match: re.Match) -> int | None:return int(round(gram_value))-def extract_serving_size_data(serving_size: str) -> tuple[int | None, str | None, float | None]:+def extract_serving_size_data(+ serving_size: str,+ language_code: str | None = None,+) -> tuple[int | None, str | None, float | None]:if not serving_size:return None, None, None# Parse textual amount/unit even if no explicit mass value is present.amount = 1.0- unit = 'Serving'+ with translation.override(language_code):+ unit = gettext('Serving')no_parentheses = re.sub(r'\([^\)]*\)', '', serving_size)no_mass = MASS_PATTERN.sub('', no_parentheses)@@ -79,7 +87,8 @@ def extract_serving_size_data(serving_size: str) -> tuple[int | None, str | Noneamount = 1.0if not unit:- unit = 'Serving'+ with translation.override(language_code):+ unit = gettext('Serving')# Prefer mass values in parenthesis, e.g. "200 ml (206 g)".parenthesis_matches = [@@ -131,8 +140,9 @@ def extract_info_from_off(product_data: dict, language: int) -> IngredientData:brand = product_data.get('brands', '')serving_size = product_data.get('serving_size', '')+ language_code = product_data.get('lang')serving_size_gram, serving_size_unit, serving_size_amount = extract_serving_size_data(- serving_size+ serving_size, language_code)# Dietary properties from OFF ingredients analysisdiff --git a/wger/nutrition/fixtures/test-ingredients.json b/wger/nutrition/fixtures/test-ingredients.jsonindex e3f3852d1..9dd88d279 100644--- a/wger/nutrition/fixtures/test-ingredients.json+++ b/wger/nutrition/fixtures/test-ingredients.json@@ -381,9 +381,8 @@"pk": 1,"model": "nutrition.ingredientweightunit","fields": {- "amount": "1","gram": 109,- "unit": 4,+ "name": "Spoon","ingredient": 1}},@@ -391,9 +390,8 @@"pk": 2,"model": "nutrition.ingredientweightunit","fields": {- "amount": "0.5","gram": 223,- "unit": 5,+ "name": "Cup","ingredient": 1}},@@ -401,9 +399,8 @@"pk": 3,"model": "nutrition.ingredientweightunit","fields": {- "amount": "1","gram": 12,- "unit": 6,+ "name": "A bit","ingredient": 1}},@@ -411,9 +408,8 @@"pk": 9874,"model": "nutrition.ingredientweightunit","fields": {- "amount": "1","gram": 12,- "unit": 6,+ "name": "A bit","ingredient": 1}},@@ -421,9 +417,8 @@"pk": 5950,"model": "nutrition.ingredientweightunit","fields": {- "amount": "1","gram": 12,- "unit": 6,+ "name": "A bit","ingredient": 1}}diff --git a/wger/nutrition/fixtures/test-weight-units.json b/wger/nutrition/fixtures/test-weight-units.jsondeleted file mode 100644index 676f30708..000000000--- a/wger/nutrition/fixtures/test-weight-units.json+++ /dev/null@@ -1,50 +0,0 @@-[- {- "pk": 1,- "model": "nutrition.weightunit",- "fields": {- "name": "Scheibe",- "language": 1- }- },- {- "pk": 2,- "model": "nutrition.weightunit",- "fields": {- "name": "Tasse",- "language": 1- }- },- {- "pk": 3,- "model": "nutrition.weightunit",- "fields": {- "name": "Handvoll",- "language": 1- }- },- {- "pk": 4,- "model": "nutrition.weightunit",- "fields": {- "name": "Spoon",- "language": 2- }- },- {- "pk": 5,- "model": "nutrition.weightunit",- "fields": {- "name": "Cup",- "language": 2- }- },- {- "pk": 6,- "model": "nutrition.weightunit",- "fields": {- "name": "A bit",- "language": 2- }- }-]\ No newline at end of filediff --git a/wger/nutrition/forms.py b/wger/nutrition/forms.pyindex 7b0094b14..61dc2b1aa 100644--- a/wger/nutrition/forms.py+++ b/wger/nutrition/forms.py@@ -55,7 +55,7 @@ class IngredientWeightUnitChoiceField(forms.ModelChoiceField):"""def label_from_instance(self, obj):- return f'{obj.amount} {obj.unit.name} = {obj.gram}g'+ return f'{obj.name} = {obj.gram}g'class UnitChooserForm(forms.Form):diff --git a/wger/nutrition/helpers.py b/wger/nutrition/helpers.pyindex 5b504eb21..20be177dd 100644--- a/wger/nutrition/helpers.py+++ b/wger/nutrition/helpers.py@@ -24,11 +24,7 @@ from decimal import Decimalfrom typing import Union# wger-from wger.nutrition.consts import (- KJ_PER_KCAL,- MEALITEM_WEIGHT_GRAM,- MEALITEM_WEIGHT_UNIT,-)+from wger.nutrition.consts import KJ_PER_KCALfrom wger.utils.constants import (CHARACTERS_TO_REMOVE_FROM_INGREDIENT_NAME,HTML_ENTITY_PATTERN,@@ -43,18 +39,6 @@ class BaseMealItem:This just provides some common helper functions"""- def get_unit_type(self):- """- Returns the type of unit used:- - a value in grams- - a 'human' unit like 'a cup' or 'a slice'- """-- if self.weight_unit:- return MEALITEM_WEIGHT_UNIT- else:- return MEALITEM_WEIGHT_GRAM-def get_nutritional_values(self, use_metric=True):"""Sums the nutritional info for the ingredient in the MealItem@@ -64,10 +48,10 @@ class BaseMealItem:values = NutritionalValues()# Calculate the base weight of the item- if self.get_unit_type() == MEALITEM_WEIGHT_GRAM:- item_weight = self.amount+ if self.weight_unit:+ item_weight = self.amount * Decimal(self.weight_unit.gram)else:- item_weight = self.amount * self.weight_unit.amount * self.weight_unit.gram+ item_weight = self.amountvalues.energy = self.ingredient.energy * item_weight / 100values.protein = self.ingredient.protein * item_weight / 100diff --git a/wger/nutrition/management/commands/import-off-products.py b/wger/nutrition/management/commands/import-off-products.pyindex e848730b8..b9754c96f 100644--- a/wger/nutrition/management/commands/import-off-products.py+++ b/wger/nutrition/management/commands/import-off-products.py@@ -34,6 +34,16 @@ logger = logging.getLogger(__name__)class Command(ImportProductCommand):"""Import an Open Food facts Dump++ Example usage:+ * Import dump (downloads the full dump, imports it and deletes it):+ python manage.py import-off-products --jsonl++ * Import dump (already downloaded in /tmo/off/):+ python manage.py import-off-products --jsonl --folder /tmp/off/++ * Import last delta update (downloads, imports and deltes the most recent delta file):+ python manage.py import-off-products --delta-updates"""help = 'Import an Open Food Facts dump'diff --git a/wger/nutrition/migrations/0031_merge_weight_unit_into_ingredient_weight_unit.py b/wger/nutrition/migrations/0031_merge_weight_unit_into_ingredient_weight_unit.pynew file mode 100644index 000000000..cf5b17bd2--- /dev/null+++ b/wger/nutrition/migrations/0031_merge_weight_unit_into_ingredient_weight_unit.py@@ -0,0 +1,38 @@+from django.db import migrations, models+from django.db.migrations.state import StateApps+++def copy_weight_unit_names(apps: StateApps, schema_editor):+ """Copy the name from WeightUnit into IngredientWeightUnit.name"""++ IngredientWeightUnit = apps.get_model('nutrition', 'IngredientWeightUnit')+ for iwu in IngredientWeightUnit.objects.select_related('unit').filter(unit__isnull=False):+ iwu.name = iwu.unit.name+ iwu.save(update_fields=['name'])+++class Migration(migrations.Migration):+ dependencies = [+ ('nutrition', '0030_add_indices'),+ ]++ operations = [+ migrations.AddField(+ model_name='ingredientweightunit',+ name='name',+ field=models.CharField(default='Serving', max_length=200, verbose_name='Name'),+ preserve_default=False,+ ),+ migrations.RunPython(copy_weight_unit_names, migrations.RunPython.noop),+ migrations.RemoveField(+ model_name='ingredientweightunit',+ name='unit',+ ),+ migrations.RemoveField(+ model_name='ingredientweightunit',+ name='amount',+ ),+ migrations.DeleteModel(+ name='WeightUnit',+ ),+ ]diff --git a/wger/nutrition/models/__init__.py b/wger/nutrition/models/__init__.pyindex 00e2a1f31..e8038c4ee 100644--- a/wger/nutrition/models/__init__.py+++ b/wger/nutrition/models/__init__.py@@ -24,4 +24,3 @@ from .meal import Mealfrom .meal_item import MealItemfrom .plan import NutritionPlanfrom .sources import Source-from .weight_unit import WeightUnitdiff --git a/wger/nutrition/models/ingredient.py b/wger/nutrition/models/ingredient.pyindex b22a5341e..71d1377b3 100644--- a/wger/nutrition/models/ingredient.py+++ b/wger/nutrition/models/ingredient.py@@ -17,10 +17,7 @@# Standard Libraryimport loggingimport uuid as uuid-from decimal import (- ROUND_HALF_UP,- Decimal,-)+from decimal import Decimalfrom json import JSONDecodeError# Django@@ -36,7 +33,9 @@ from django.core.validators import (from django.db import modelsfrom django.http import HttpRequestfrom django.urls import reverse+from django.utils import translationfrom django.utils.text import slugify+from django.utils.translation import gettext# Third Partyfrom openfoodfacts import API@@ -52,6 +51,7 @@ from wger.nutrition.consts import (ENERGY_FACTOR,KJ_PER_KCAL,)+from wger.nutrition.dataclasses import IngredientDatafrom wger.nutrition.managers import ApproximateCountManagerfrom wger.nutrition.models.ingredient_category import IngredientCategoryfrom wger.nutrition.models.sources import Source@@ -493,7 +493,7 @@ class Ingredient(AbstractLicenseModel, models.Model):fetch_ingredient_image_task.delay(self.pk)- def update_or_create_serving_unit_from_off(self, ingredient_data):+ def update_or_create_serving_unit_from_off(self, ingredient_data: IngredientData):"""Fetch serving size from OFF and update or create a record of it.@@ -513,42 +513,35 @@ class Ingredient(AbstractLicenseModel, models.Model):if not gram:return False, False- # Local imports to avoid model import cycles.+ # Local import to avoid model import cycles.# wger- from wger.nutrition.models import (- IngredientWeightUnit,- WeightUnit,- )+ from wger.nutrition.models import IngredientWeightUnit- unit = WeightUnit.objects.filter(- language_id=self.language_id,- name__iexact=ingredient_data.serving_size_unit,- ).first()- if not unit:- unit = WeightUnit.objects.create(- language_id=self.language_id,- name=ingredient_data.serving_size_unit,- )+ amount = ingredient_data.serving_size_amount or 1+ unit = ingredient_data.serving_size_unit- amount = ingredient_data.serving_size_amount or 1 # if no amount is given, assume 1.- amount = Decimal(str(amount)).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)+ # Build a descriptive name, e.g. "1 Portion (2 biscuits)" for amount > 1+ if amount > 1:+ with translation.override(self.language.short_name):+ portion = gettext('Portion')+ name = f'1 {portion} ({amount:g} {unit})'+ else:+ name = unitexisting_weight_unit = IngredientWeightUnit.objects.filter(ingredient=self,- unit=unit,+ name__iexact=name,).first()if existing_weight_unit:existing_weight_unit.gram = gram- existing_weight_unit.amount = amount- existing_weight_unit.save(update_fields=['gram', 'amount'])+ existing_weight_unit.save(update_fields=['gram'])return False, True # (created, updated)else:IngredientWeightUnit.objects.create(ingredient=self,- unit=unit,+ name=name,gram=gram,- amount=amount,)return True, False # (created, updated)diff --git a/wger/nutrition/models/ingredient_weight_unit.py b/wger/nutrition/models/ingredient_weight_unit.pyindex e31073721..1e9019d76 100644--- a/wger/nutrition/models/ingredient_weight_unit.py+++ b/wger/nutrition/models/ingredient_weight_unit.py@@ -22,7 +22,6 @@ from django.db import models# Localfrom .ingredient import Ingredient-from .weight_unit import WeightUnitlogger = logging.getLogger(__name__)@@ -39,20 +38,12 @@ class IngredientWeightUnit(models.Model):editable=False,on_delete=models.CASCADE,)- unit = models.ForeignKey(- WeightUnit,- verbose_name='Weight unit',- on_delete=models.CASCADE,+ name = models.CharField(+ max_length=200,+ verbose_name='Name',)gram = models.IntegerField(verbose_name='Amount in grams')- 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):"""@@ -65,4 +56,4 @@ class IngredientWeightUnit(models.Model):Return a more human-readable representation"""- return f'{self.amount if self.amount > 1 else ""}{self.unit.name} ({self.gram}g)'+ return f'{self.name} ({self.gram}g)'diff --git a/wger/nutrition/models/weight_unit.py b/wger/nutrition/models/weight_unit.pydeleted file mode 100644index cc069364f..000000000--- a/wger/nutrition/models/weight_unit.py+++ /dev/null@@ -1,56 +0,0 @@-# This file is part of wger Workout Manager <https://github.com/wger-project>.-# Copyright (C) 2013 - 2021 wger Team-#-# wger 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.-#-# wger 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 Affero General Public License for more details.-#-# You should have received a copy of the GNU Affero General Public License-# along with this program. If not, see <http://www.gnu.org/licenses/>.--# Django-from django.db import models--# wger-from wger.core.models import Language---class WeightUnit(models.Model):- """- A more human usable weight unit (spoon, table, slice...)- """-- language = models.ForeignKey(- Language,- verbose_name='Language',- editable=False,- on_delete=models.CASCADE,- )- name = models.CharField(- max_length=200,- verbose_name='Name',- )-- # Metaclass to set some other properties- class Meta:- ordering = [- 'name',- ]-- def __str__(self):- """- Return a more human-readable representation- """- return self.name-- def get_owner_object(self):- """- Weight unit has no owner information- """- return Nonediff --git a/wger/nutrition/templates/ingredient/view.html b/wger/nutrition/templates/ingredient/view.htmlindex 72e0eb91b..0060c942d 100644--- a/wger/nutrition/templates/ingredient/view.html+++ b/wger/nutrition/templates/ingredient/view.html@@ -173,7 +173,9 @@ $(document).ready(function() {{% endblock %}-+{# #}+{# Sidebar #}+{# #}{% block sidebar %}{% if perms.nutrition.delete_ingredient %}@@ -194,7 +196,7 @@ $(document).ready(function() {{% for unit in ingredient.ingredientweightunit_set.select_related %}<tr><td>- {{unit.amount}} {{unit.unit.name}} = {{unit.gram}}g+ {{unit.amount}} {{unit.name}} = {{unit.gram}}g<div class="dropdown float-end"><button type="button" class="btn btn-light dropdown-toggle btn-sm" data-bs-toggle="dropdown"><span class="{% fa_class 'cog' %}"></span>@@ -231,8 +233,6 @@ $(document).ready(function() {{% endblock %}--{# #}{# Options #}{# #}diff --git a/wger/nutrition/templates/units/list.html b/wger/nutrition/templates/units/list.htmldeleted file mode 100644index 2dbc3fc32..000000000--- a/wger/nutrition/templates/units/list.html+++ /dev/null@@ -1,52 +0,0 @@-{% extends "base.html" %}-{% load i18n %}-{% load static %}-{% load wger_extras %}--{% block title %}{% translate "Ingredient weight units" %}{% endblock %}---{% block content %}- <ul class="list-group">- {% for unit in unit_list %}- <li class="list-group-item ">- <div class="btn-group float-end">- <button type="button" class="btn btn-light dropdown-toggle btn-sm"- data-bs-toggle="dropdown">- <span class="{% fa_class 'cog' %}"></span>- </button>- <div class="dropdown-menu dropdown-menu-right" role="menu">- {% translate 'Edit' as text %}- {% url 'nutrition:weight_unit:edit' unit.id as url %}- {% modal_link url=url text=text css_class='dropdown-item' %}-- <div class="dropdown-divider"></div>-- {% translate 'Delete' as text %}- {% url 'nutrition:weight_unit:delete' unit.id as url %}- {% modal_link url=url text=text css_class='dropdown-item' %}- </div>- </div>- {{ unit.name }}- </li>- {% empty %}- <li class="list-group-item">- {% translate "Nothing found" %}- </li>- {% endfor %}- </ul>--- {% pagination paginator page_obj %}-{% endblock %}-----{# #}-{# Options #}-{# #}-{% block options %}- {% translate 'Add new weight unit' as text %}- {% modal_link url='nutrition:weight_unit:add' text=text %}-{% endblock %}diff --git a/wger/nutrition/tests/test_ingredient.py b/wger/nutrition/tests/test_ingredient.pyindex d70827c91..53c5e3b80 100644--- a/wger/nutrition/tests/test_ingredient.py+++ b/wger/nutrition/tests/test_ingredient.py@@ -47,7 +47,6 @@ from wger.nutrition.models import (IngredientWeightUnit,Meal,Source,- WeightUnit,)from wger.nutrition.models.image import Imagefrom wger.utils.constants import NUTRITION_TAB@@ -376,15 +375,15 @@ class IngredientValuesTestCase(WgerTestCase):self.assertEqual(result,{- 'sodium': 0.612135,- 'energy': 196.24,- # 'energy_kilojoule': '821.07',- 'fat': 9.13185,+ 'sodium': 1.22427,+ 'energy': 392.48,+ # 'energy_kilojoule': '1642.14',+ 'fat': 18.2637,'carbohydrates_sugar': None,- 'fat_saturated': 3.61706,+ 'fat_saturated': 7.23412,'fiber': None,- 'protein': 28.57745,- 'carbohydrates': 0.139375,+ 'protein': 57.1549,+ 'carbohydrates': 0.27875,},)@@ -545,42 +544,6 @@ class IngredientModelTestCase(WgerTestCase):self.assertTrue(ingredient.is_vegan)self.assertTrue(ingredient.is_vegetarian)- @patch('openfoodfacts.api.ProductResource.get')- def test_fetch_from_off_creates_serving_unit(self, mock_api: MagicMock):- self.off_response['serving_size'] = '2 biscuits (30 g)'- mock_api.return_value = self.off_response-- ingredient = Ingredient.fetch_ingredient_from_off('1234')-- unit = WeightUnit.objects.get(language=ingredient.language, name='biscuits')- ingredient_unit = IngredientWeightUnit.objects.get(ingredient=ingredient, unit=unit)- self.assertEqual(ingredient_unit.gram, 30)- self.assertEqual(ingredient_unit.amount, Decimal('2.00'))-- @patch('openfoodfacts.api.ProductResource.get')- def test_fetch_from_off_creates_volume_serving_unit(self, mock_api: MagicMock):- self.off_response['serving_size'] = '200 ml (206 g)'- mock_api.return_value = self.off_response-- ingredient = Ingredient.fetch_ingredient_from_off('1234')-- unit = WeightUnit.objects.get(language=ingredient.language, name='ml')- ingredient_unit = IngredientWeightUnit.objects.get(ingredient=ingredient, unit=unit)- self.assertEqual(ingredient_unit.gram, 206)- self.assertEqual(ingredient_unit.amount, Decimal('200.00'))-- @patch('openfoodfacts.api.ProductResource.get')- def test_fetch_from_off_creates_volume_serving_unit_without_mass(self, mock_api: MagicMock):- self.off_response['serving_size'] = '200 ml'- mock_api.return_value = self.off_response-- ingredient = Ingredient.fetch_ingredient_from_off('1234')-- unit = WeightUnit.objects.get(language=ingredient.language, name='ml')- ingredient_unit = IngredientWeightUnit.objects.get(ingredient=ingredient, unit=unit)- self.assertEqual(ingredient_unit.gram, 200)- self.assertEqual(ingredient_unit.amount, Decimal('200.00'))-@patch('openfoodfacts.api.ProductResource.get')def test_fetch_from_off_updates_existing_serving_unit(self, mock_api: MagicMock):self.off_response['serving_size'] = '2 biscuits (30 g)'@@ -592,10 +555,10 @@ class IngredientModelTestCase(WgerTestCase):extract_info_from_off(self.off_response, ingredient.language_id))- unit = WeightUnit.objects.get(language=ingredient.language, name='biscuits')- ingredient_unit = IngredientWeightUnit.objects.get(ingredient=ingredient, unit=unit)+ ingredient_unit = IngredientWeightUnit.objects.get(+ ingredient=ingredient, name='1 Portion (2 biscuits)'+ )self.assertEqual(ingredient_unit.gram, 25)- self.assertEqual(ingredient_unit.amount, Decimal('2.00'))@patch('openfoodfacts.api.ProductResource.get')def test_fetch_from_off_success_long_name(self, mock_api: MagicMock):@@ -668,8 +631,8 @@ class IngredientModelTestCase(WgerTestCase):ingredient.code = '1234'ingredient.save(update_fields=['source_name', 'code'])ingredient.ingredientweightunit_set.get_or_create(- unit=WeightUnit.objects.get(pk=5),- defaults={'gram': 15, 'amount': Decimal('1.00')},+ name='Cup',+ defaults={'gram': 15},)created, updated = ingredient.sync_serving_unit_from_off_if_missing()diff --git a/wger/nutrition/tests/test_nutritional_calculations.py b/wger/nutrition/tests/test_nutritional_calculations.pyindex 4d0e38ef0..4db8fc4c1 100644--- a/wger/nutrition/tests/test_nutritional_calculations.py+++ b/wger/nutrition/tests/test_nutritional_calculations.py@@ -133,6 +133,88 @@ class NutritionalValuesCalculationsTestCase(WgerTestCase):plan_nutritional_values = plan.get_nutritional_values()self.assertEqual(meal_nutritional_values, plan_nutritional_values['total'])+ def test_calculations_with_weight_units(self):+ """+ Tests the nutritional value calculations when using weight units+ """+ plan = models.NutritionPlan(user_id=1)+ plan.save()++ meal = models.Meal(order=1)+ meal.plan = plan+ meal.save()++ ingredient = models.Ingredient.objects.get(pk=1)++ # 3 x "A bit" (12g each) = 36g+ item = models.MealItem()+ item.meal = meal+ item.ingredient = ingredient+ item.order = 1+ item.amount = 3+ item.weight_unit_id = 3+ item.save()++ item_values = item.get_nutritional_values()+ expected_weight = Decimal(3) * Decimal(12) # 36g+ self.assertAlmostEqual(item_values.energy, ingredient.energy * expected_weight / 100, 2)+ self.assertAlmostEqual(item_values.protein, ingredient.protein * expected_weight / 100, 2)+ self.assertAlmostEqual(item_values.fat, ingredient.fat * expected_weight / 100, 2)++ # 1 x "Spoon" (109g) = 109g+ item.delete()+ item = models.MealItem()+ item.meal = meal+ item.ingredient = ingredient+ item.order = 1+ item.amount = 1+ item.weight_unit_id = 1+ item.save()++ item_values = item.get_nutritional_values()+ expected_weight = Decimal(109)+ self.assertAlmostEqual(item_values.energy, ingredient.energy * expected_weight / 100, 2)++ # 2 x "Cup" (223g each) = 446g+ item.delete()+ item = models.MealItem()+ item.meal = meal+ item.ingredient = ingredient+ item.order = 1+ item.amount = 2+ item.weight_unit_id = 2+ item.save()++ item_values = item.get_nutritional_values()+ expected_weight = Decimal(2) * Decimal(223) # 446g+ self.assertAlmostEqual(item_values.energy, ingredient.energy * expected_weight / 100, 2)+ self.assertAlmostEqual(item_values.protein, ingredient.protein * expected_weight / 100, 2)++ def test_calculations_with_no_weight_unit(self):+ """+ Tests that amount is treated as grams when no weight unit is set+ """+ plan = models.NutritionPlan(user_id=1)+ plan.save()++ meal = models.Meal(order=1)+ meal.plan = plan+ meal.save()++ ingredient = models.Ingredient.objects.get(pk=1)++ item = models.MealItem()+ item.meal = meal+ item.ingredient = ingredient+ item.order = 1+ item.amount = 250+ item.weight_unit = None+ item.save()++ item_values = item.get_nutritional_values()+ self.assertAlmostEqual(item_values.energy, ingredient.energy * Decimal(250) / 100, 2)+ self.assertAlmostEqual(item_values.protein, ingredient.protein * Decimal(250) / 100, 2)+def test_calculations_user(self):"""Tests the calculationsdiff --git a/wger/nutrition/tests/test_off.py b/wger/nutrition/tests/test_off.pyindex 526379ef5..980c42edf 100644--- a/wger/nutrition/tests/test_off.py+++ b/wger/nutrition/tests/test_off.py@@ -54,6 +54,7 @@ class ExtractInfoFromOffTestCase(SimpleTestCase):'fiber_100g': None,'other_stuff': 'is ignored',},+ 'serving_size': '',}def test_regular_response(self):diff --git a/wger/nutrition/tests/test_weight_unit.py b/wger/nutrition/tests/test_weight_unit.pydeleted file mode 100644index e3e9f682e..000000000--- a/wger/nutrition/tests/test_weight_unit.py+++ /dev/null@@ -1,120 +0,0 @@-# This file is part of wger Workout Manager.-#-# wger 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.-#-# wger 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/>.--# Django-from django.urls import reverse--# wger-from wger.core.tests import api_base_test-from wger.core.tests.base_testcase import (- WgerAddTestCase,- WgerDeleteTestCase,- WgerEditTestCase,- WgerTestCase,-)-from wger.nutrition.models import WeightUnit-from wger.utils.constants import PAGINATION_OBJECTS_PER_PAGE---class WeightUnitRepresentationTestCase(WgerTestCase):- """- Test the representation of a model- """-- def test_representation(self):- """- Test that the representation of an object is correct- """- self.assertEqual(str(WeightUnit.objects.get(pk=1)), 'Scheibe')---class AddWeightUnitTestCase(WgerAddTestCase):- """- Tests adding a new weight unit- """-- object_class = WeightUnit- url = 'nutrition:weight_unit:add'- data = {'name': 'A new weight unit'}---class DeleteWeightUnitTestCase(WgerDeleteTestCase):- """- Tests deleting a weight unit- """-- object_class = WeightUnit- url = 'nutrition:weight_unit:delete'- pk = 1---class EditWeightUnitTestCase(WgerEditTestCase):- """- Tests editing a weight unit- """-- object_class = WeightUnit- url = 'nutrition:weight_unit:edit'- pk = 1- data = {'name': 'A new name'}---class WeightUnitOverviewTestCase(WgerTestCase):- """- 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('nutrition:weight_unit:add'), data)-- # Page exists and the pagination works- response = self.client.get(reverse('nutrition: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('nutrition: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('nutrition: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('nutrition: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('nutrition:weight_unit:list'), {'page': 100})- self.assertEqual(response.status_code, 404)-- response = self.client.get(reverse('nutrition:weight_unit:list'), {'page': 'foobar'})- self.assertEqual(response.status_code, 404)---class WeightUnitApiTestCase(api_base_test.ApiBaseResourceTestCase):- """- Tests the weight unit overview resource- """-- pk = 1- resource = WeightUnit- private_resource = False- data = {'name': 'The weight unit name'}diff --git a/wger/nutrition/tests/test_weight_unit_ingredient.py b/wger/nutrition/tests/test_weight_unit_ingredient.pyindex 4fc75e13d..07c3fba38 100644--- a/wger/nutrition/tests/test_weight_unit_ingredient.py+++ b/wger/nutrition/tests/test_weight_unit_ingredient.py@@ -14,10 +14,7 @@# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.# Django-from django.urls import (- reverse,- reverse_lazy,-)+from django.urls import reverse_lazy# wgerfrom wger.core.tests import api_base_test@@ -27,10 +24,7 @@ from wger.core.tests.base_testcase import (WgerEditTestCase,WgerTestCase,)-from wger.nutrition.models import (- IngredientWeightUnit,- WeightUnit,-)+from wger.nutrition.models import IngredientWeightUnitclass WeightUnitIngredientRepresentationTestCase(WgerTestCase):@@ -53,9 +47,8 @@ class AddWeightUnitIngredientTestCase(WgerAddTestCase):object_class = IngredientWeightUniturl = reverse_lazy('nutrition:unit_ingredient:add', kwargs={'ingredient_pk': 1})data = {- 'unit': 5,+ 'name': 'Cup','gram': 123,- 'amount': 1,}@@ -78,48 +71,11 @@ class EditWeightUnitTestCase(WgerEditTestCase):url = 'nutrition:unit_ingredient:edit'pk = 1data = {- 'unit': 5,+ 'name': 'Tablespoon','gram': 10,- 'amount': 0.3,}-class WeightUnitFormTestCase(WgerTestCase):- """- Tests the form for the weight units- """-- def test_add_weight_unit(self):- """- Tests the form in the add view- """- self.user_login('admin')- response = self.client.get(- reverse('nutrition:unit_ingredient:add', kwargs={'ingredient_pk': 1})- )-- choices = [text for value, text in response.context['form']['unit'].field.choices]- for unit in WeightUnit.objects.all():- if unit.language_id == 1:- self.assertNotIn(unit.name, choices)- else:- self.assertIn(unit.name, choices)-- def test_edit_weight_unit(self):- """- Tests that the form in the edit view only shows weight units in the user's language- """- self.user_login('admin')- response = self.client.get(reverse('nutrition:unit_ingredient:edit', kwargs={'pk': 1}))-- choices = [text for value, text in response.context['form']['unit'].field.choices]- for unit in WeightUnit.objects.all():- if unit.language_id == 1:- self.assertNotIn(unit.name, choices)- else:- self.assertIn(unit.name, choices)--class WeightUnitToIngredientApiTestCase(api_base_test.ApiBaseResourceTestCase):"""Tests the weight unit to ingredient API resource@@ -129,9 +85,8 @@ class WeightUnitToIngredientApiTestCase(api_base_test.ApiBaseResourceTestCase):resource = IngredientWeightUnitprivate_resource = Falsedata = {- 'amount': '1','gram': 240,'id': 1,'ingredient': '1',- 'unit': '1',+ 'name': 'Spoon',}diff --git a/wger/nutrition/urls.py b/wger/nutrition/urls.pyindex 9e084c209..8e87637bb 100644--- a/wger/nutrition/urls.py+++ b/wger/nutrition/urls.py@@ -26,7 +26,6 @@ from wger.nutrition.views import (calculator,ingredient,plan,- unit,unit_ingredient,)@@ -89,30 +88,6 @@ patterns_ingredient = [),]-# sub patterns for weight units-patterns_weight_unit = [- path(- 'list/',- unit.WeightUnitListView.as_view(),- name='list',- ),- path(- 'add/',- unit.WeightUnitCreateView.as_view(),- name='add',- ),- path(- '<int:pk>/delete/',- unit.WeightUnitDeleteView.as_view(),- name='delete',- ),- path(- '<int:pk>/edit/',- unit.WeightUnitUpdateView.as_view(),- name='edit',- ),-]-# sub patterns for weight units / ingredient cross tablepatterns_unit_ingredient = [path(@@ -175,13 +150,6 @@ urlpatterns = [namespace='ingredient',),),- path(- 'unit/',- include(- (patterns_weight_unit, 'weight_unit'),- namespace='weight_unit',- ),- ),path('unit-to-ingredient/',include(diff --git a/wger/nutrition/views/plan.py b/wger/nutrition/views/plan.pyindex ad4f601b6..cf0c3d108 100644--- a/wger/nutrition/views/plan.py+++ b/wger/nutrition/views/plan.py@@ -41,7 +41,6 @@ from reportlab.platypus import ()# wger-from wger.nutrition.consts import MEALITEM_WEIGHT_GRAMfrom wger.nutrition.models import (Meal,MealItem,@@ -165,10 +164,10 @@ def export_pdf(request, id: int):ingredient_markers.append(len(data))p = Paragraph(f'<para>{item.ingredient.name}</para>', styleSheet['Normal'])- if item.get_unit_type() == MEALITEM_WEIGHT_GRAM:- unit_name = 'g'+ if item.weight_unit:+ unit_name = ' × ' + item.weight_unit.nameelse:- unit_name = ' × ' + item.weight_unit.unit.name+ unit_name = 'g'data.append([Paragraph('{0:.0f}{1}'.format(item.amount, unit_name), styleSheet['Normal']), p]diff --git a/wger/nutrition/views/unit.py b/wger/nutrition/views/unit.pydeleted file mode 100644index bd5ec3979..000000000--- a/wger/nutrition/views/unit.py+++ /dev/null@@ -1,144 +0,0 @@-# -*- coding: utf-8 -*---# This file is part of wger Workout Manager.-#-# wger 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.-#-# wger 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--# Standard Library-import logging--# Django-from django.contrib.auth.mixins import (- LoginRequiredMixin,- PermissionRequiredMixin,-)-from django.urls import (- reverse,- reverse_lazy,-)-from django.utils.translation import (- gettext as _,- gettext_lazy,-)-from django.views.generic import (- CreateView,- DeleteView,- ListView,- UpdateView,-)--# wger-from wger.nutrition.models import WeightUnit-from wger.utils.constants import PAGINATION_OBJECTS_PER_PAGE-from wger.utils.generic_views import (- WgerDeleteMixin,- WgerFormMixin,-)-from wger.utils.language import load_language---logger = logging.getLogger(__name__)-# ************************-# Weight units functions-# ************************---class WeightUnitListView(PermissionRequiredMixin, ListView):- """- Generic view to list all weight units- """-- model = WeightUnit- template_name = 'units/list.html'- context_object_name = 'unit_list'- paginate_by = PAGINATION_OBJECTS_PER_PAGE- permission_required = 'nutrition.add_ingredientweightunit'-- def get_queryset(self):- """- Only show ingredient units in the current user's language- """- return WeightUnit.objects.filter(language=load_language())---class WeightUnitCreateView(- WgerFormMixin,- LoginRequiredMixin,- PermissionRequiredMixin,- CreateView,-):- """- Generic view to add a new weight unit for ingredients- """-- model = WeightUnit- fields = ('name',)- title = gettext_lazy('Add new weight unit')- permission_required = 'nutrition.add_ingredientweightunit'-- def get_success_url(self):- return reverse('nutrition:weight_unit:list')-- def form_valid(self, form):- form.instance.language = load_language()- return super(WeightUnitCreateView, self).form_valid(form)---class WeightUnitDeleteView(- WgerDeleteMixin,- LoginRequiredMixin,- PermissionRequiredMixin,- DeleteView,-):- """- Generic view to delete a weight unit- """-- model = WeightUnit- success_url = reverse_lazy('nutrition:weight_unit:list')- permission_required = 'nutrition.delete_ingredientweightunit'- messages = gettext_lazy('Successfully deleted')-- def get_context_data(self, **kwargs):- """- Send some additional data to the template- """- context = super(WeightUnitDeleteView, self).get_context_data(**kwargs)- context['title'] = _('Delete {0}?').format(self.object)- return context---class WeightUnitUpdateView(- WgerFormMixin,- LoginRequiredMixin,- PermissionRequiredMixin,- UpdateView,-):- """- Generic view to update an weight unit- """-- model = WeightUnit- fields = ('name',)- permission_required = 'nutrition.change_ingredientweightunit'-- def get_success_url(self):- return reverse('nutrition:weight_unit:list')-- def get_context_data(self, **kwargs):- """- Send some additional data to the template- """- context = super(WeightUnitUpdateView, self).get_context_data(**kwargs)- context['title'] = _('Edit {0}').format(self.object)- return contextdiff --git a/wger/nutrition/views/unit_ingredient.py b/wger/nutrition/views/unit_ingredient.pyindex e548f1086..477fae72d 100644--- a/wger/nutrition/views/unit_ingredient.py+++ b/wger/nutrition/views/unit_ingredient.py@@ -22,10 +22,7 @@ from django.contrib.auth.mixins import (LoginRequiredMixin,PermissionRequiredMixin,)-from django.forms import (- ModelChoiceField,- ModelForm,-)+from django.forms import ModelFormfrom django.shortcuts import get_object_or_404from django.urls import reversefrom django.utils.translation import gettext_lazy@@ -39,13 +36,11 @@ from django.views.generic import (from wger.nutrition.models import (Ingredient,IngredientWeightUnit,- WeightUnit,)from wger.utils.generic_views import (WgerDeleteMixin,WgerFormMixin,)-from wger.utils.language import load_languagelogger = logging.getLogger(__name__)@@ -83,11 +78,9 @@ class WeightUnitIngredientCreateView("""class IngredientWeightUnitForm(ModelForm):- unit = ModelChoiceField(queryset=WeightUnit.objects.filter(language=load_language()))-class Meta:model = IngredientWeightUnit- fields = ('unit', 'gram', 'amount')+ fields = ('name', 'gram')return IngredientWeightUnitForm@@ -115,11 +108,9 @@ class WeightUnitIngredientUpdateView("""class IngredientWeightUnitForm(ModelForm):- unit = ModelChoiceField(queryset=WeightUnit.objects.filter(language=load_language()))-class Meta:model = IngredientWeightUnit- fields = ('unit', 'gram', 'amount')+ fields = ('name', 'gram')return IngredientWeightUnitFormdiff --git a/wger/urls.py b/wger/urls.pyindex 322e86358..43451ccac 100644--- a/wger/urls.py+++ b/wger/urls.py@@ -214,7 +214,6 @@ router.register(r'ingredient', nutrition_api_views.IngredientViewSet, basename='router.register(r'ingredientinfo', nutrition_api_views.IngredientInfoViewSet, basename='api-ingredientinfo')-router.register(r'weightunit', nutrition_api_views.WeightUnitViewSet, basename='weightunit')router.register(r'ingredientweightunit',nutrition_api_views.IngredientWeightUnitViewSet,