From 8d1afab9e8d5a430e3329bbac36c0df283a14a9f Mon Sep 17 00:00:00 2001 From: Joren de Graaf Date: Sat, 3 Oct 2026 21:25:56 +0200 Subject: [PATCH] adding food logging, phase 5 --- main/food/forms.py | 110 +++++++++- ...02_foodportion_food_one_default_portion.py | 19 ++ main/food/models.py | 7 +- main/food/services/diary.py | 2 +- main/food/static/food/food.css | 3 + main/food/static/food/portions.js | 19 ++ main/food/templates/food/add.html | 47 +---- main/food/templates/food/edit.html | 5 +- main/food/templates/food/manual.html | 2 +- .../templates/food/partials/add_content.html | 49 +++++ .../food/partials/diary_content.html | 1 + .../templates/food/partials/edit_content.html | 15 ++ .../food/partials/favourite_button.html | 4 + .../food/partials/favourite_update.html | 3 + .../food/partials/portion_fields.html | 15 ++ .../templates/food/partials/product_list.html | 5 + main/food/test_csv_export.py | 74 +++++++ main/food/test_repeat_logging.py | 120 +++++++++++ main/food/urls.py | 2 + main/food/views.py | 198 ++++++++++++++++-- 20 files changed, 627 insertions(+), 73 deletions(-) create mode 100644 main/food/migrations/0002_foodportion_food_one_default_portion.py create mode 100644 main/food/static/food/portions.js create mode 100644 main/food/templates/food/partials/add_content.html create mode 100644 main/food/templates/food/partials/edit_content.html create mode 100644 main/food/templates/food/partials/favourite_button.html create mode 100644 main/food/templates/food/partials/favourite_update.html create mode 100644 main/food/templates/food/partials/portion_fields.html create mode 100644 main/food/templates/food/partials/product_list.html create mode 100644 main/food/test_csv_export.py create mode 100644 main/food/test_repeat_logging.py diff --git a/main/food/forms.py b/main/food/forms.py index 4c1f0fa..a280cc6 100644 --- a/main/food/forms.py +++ b/main/food/forms.py @@ -1,27 +1,70 @@ from django import forms +from decimal import Decimal -from .models import FoodLogEntry, FoodProduct, MealType +from .models import FoodLogEntry, FoodPortion, FoodProduct class ManualFoodForm(forms.ModelForm): + basis_amount = forms.DecimalField(min_value=Decimal('0.001'), max_digits=10, decimal_places=3, + initial=100, label='Nutrition basis amount') class Meta: model = FoodProduct fields = ('product_name', 'brand', 'barcode', 'base_unit', 'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', 'fibre_100', 'sugars_100', 'salt_100') labels = { - 'energy_kcal_100': 'Calories per 100 g or ml', - 'carbohydrates_100': 'Carbohydrates per 100 g or ml', - 'protein_100': 'Protein per 100 g or ml', - 'fat_100': 'Fat per 100 g or ml', + 'energy_kcal_100': 'Calories for base quantity', + 'carbohydrates_100': 'Carbohydrates for base quantity', + 'protein_100': 'Protein for base quantity', + 'fat_100': 'Fat for base quantity', + 'fibre_100': 'Fibre for base quantity (optional)', + 'sugars_100': 'Sugars for base quantity (optional)', + 'salt_100': 'Salt for base quantity (optional)', } def __init__(self, *args, **kwargs): + self.user = kwargs.pop('user', None) super().__init__(*args, **kwargs) self.fields['barcode'].required = False for field in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100'): self.fields[field].required = True + def clean_barcode(self): + barcode = self.cleaned_data['barcode'].strip() + if barcode and (not barcode.isascii() or not barcode.isdigit()): + raise forms.ValidationError('Enter a numeric barcode.') + if barcode and self.user and FoodProduct.objects.filter(owner=self.user, barcode=barcode).exists(): + raise forms.ValidationError('This barcode is already saved in your foods.') + return barcode + + def clean(self): + data = super().clean() + basis = data.get('basis_amount') + if basis: + factor = Decimal('100') / basis + for name in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', + 'fibre_100', 'sugars_100', 'salt_100'): + value = data.get(name) + if value is not None and value * factor > Decimal('9999999.999'): + self.add_error(name, 'This amount is too large for the chosen base quantity.') + return data + + def save(self, commit=True): + product = super().save(commit=False) + factor = Decimal('100') / self.cleaned_data['basis_amount'] + for name in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', + 'fibre_100', 'sugars_100', 'salt_100'): + value = self.cleaned_data[name] + setattr(product, name, (value * factor).quantize(Decimal('0.001')) if value is not None else None) + if commit: + product.save() + return product + class FoodLogForm(forms.ModelForm): + portion = forms.ChoiceField(label='Portion', required=False) + save_portion = forms.BooleanField(required=False, label='Save custom amount as a portion') + new_portion_label = forms.CharField(max_length=100, required=False, label='New portion label') + make_default = forms.BooleanField(required=False, label='Use this portion by default') + class Meta: model = FoodLogEntry fields = ('meal', 'amount', 'unit', 'portion_label_snapshot') @@ -33,9 +76,66 @@ class FoodLogForm(forms.ModelForm): self.product = product or getattr(self.instance, 'product', None) if self.product and self.product.pk: self.fields['unit'].initial = self.product.base_unit + unit = self.product.base_unit + choices = [('custom', 'Custom amount'), ('base', f'100 {unit}')] + if self.product.serving_amount and self.product.serving_unit == unit: + choices.append(('serving', f'Serving — {self.product.serving_amount:g} {unit}')) + portions = list(FoodPortion.objects.filter(product=self.product, user=self.product.owner).order_by('label')) + choices.extend((f'portion:{item.pk}', f'{item.label} — {item.amount:g} {item.unit}') for item in portions) + self.fields['portion'].choices = choices + self.portions = {str(item.pk): item for item in portions} + default = next((item for item in portions if item.is_default), None) + if default is None: + last = self.product.log_entries.filter(user=self.product.owner).order_by('-created_at').first() + default = next((item for item in portions if last and item.label == last.portion_label_snapshot and + item.amount == last.amount and item.unit == last.unit), None) + if self.instance.pk: + selected = next((item for item in portions if item.label == self.instance.portion_label_snapshot and + item.amount == self.instance.amount and item.unit == self.instance.unit), None) + self.fields['portion'].initial = f'portion:{selected.pk}' if selected else 'custom' + elif default: + self.fields['portion'].initial = f'portion:{default.pk}' + self.fields['amount'].initial = default.amount + elif self.product.serving_amount and self.product.serving_unit == unit: + self.fields['portion'].initial = 'serving' + self.fields['amount'].initial = self.product.serving_amount + else: + self.fields['portion'].initial = 'base' + self.fields['amount'].initial = 100 + self.fields['amount'].required = False def clean_unit(self): unit = self.cleaned_data['unit'] if self.product and unit != self.product.base_unit: raise forms.ValidationError('Use the same unit as the product nutrition basis.') return unit + + def clean(self): + data = super().clean() + selected = data.get('portion') or 'custom' + if not self.product or not selected: + return data + if selected == 'base': + data['amount'], data['portion_label_snapshot'] = Decimal('100'), '' + elif selected == 'serving': + data['amount'], data['portion_label_snapshot'] = self.product.serving_amount, 'Serving' + elif selected.startswith('portion:'): + portion = self.portions.get(selected.partition(':')[2]) + if not portion: + self.add_error('portion', 'Choose a valid portion.') + else: + data['amount'], data['portion_label_snapshot'] = portion.amount, portion.label + elif selected == 'custom': + if data.get('amount') is None or data['amount'] <= 0: + self.add_error('amount', 'Enter an amount greater than zero.') + if data.get('save_portion'): + label = (data.get('new_portion_label') or '').strip() + if not label: + self.add_error('new_portion_label', 'Enter a label for the saved portion.') + elif FoodPortion.objects.filter(user=self.product.owner, product=self.product, label=label).exists(): + self.add_error('new_portion_label', 'You already have a portion with this label.') + else: + data['portion_label_snapshot'] = label + elif data.get('make_default'): + self.add_error('make_default', 'Save the portion before making it the default.') + return data diff --git a/main/food/migrations/0002_foodportion_food_one_default_portion.py b/main/food/migrations/0002_foodportion_food_one_default_portion.py new file mode 100644 index 0000000..82fa6d6 --- /dev/null +++ b/main/food/migrations/0002_foodportion_food_one_default_portion.py @@ -0,0 +1,19 @@ +# Generated by Django 6.1.1 on 2026-10-03 19:10 + +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('food', '0001_initial'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AddConstraint( + model_name='foodportion', + constraint=models.UniqueConstraint(condition=models.Q(('is_default', True)), fields=('user', 'product'), name='food_one_default_portion'), + ), + ] diff --git a/main/food/models.py b/main/food/models.py index d05cd83..4acad1d 100644 --- a/main/food/models.py +++ b/main/food/models.py @@ -117,9 +117,14 @@ class FoodPortion(models.Model): updated_at = models.DateTimeField(auto_now=True) class Meta: - constraints = [models.UniqueConstraint(fields=('user', 'product', 'label'), name='food_unique_portion_label')] + constraints = [ + models.UniqueConstraint(fields=('user', 'product', 'label'), name='food_unique_portion_label'), + models.UniqueConstraint(fields=('user', 'product'), condition=Q(is_default=True), name='food_one_default_portion'), + ] def clean(self): super().clean() if self.product_id and self.user_id and self.product.owner_id != self.user_id: raise ValidationError({'product': 'Choose one of your own food products.'}) + if self.product_id and self.unit != self.product.base_unit: + raise ValidationError({'unit': 'Use the same unit as the product nutrition basis.'}) diff --git a/main/food/services/diary.py b/main/food/services/diary.py index 1bfdab9..3983e3d 100644 --- a/main/food/services/diary.py +++ b/main/food/services/diary.py @@ -24,7 +24,7 @@ def selected_date(request): def diary_context(user, day): goals, _ = UserSettings.objects.get_or_create(user=user) - entries = list(FoodLogEntry.objects.filter(user=user, date=day).select_related('product')) + entries = list(FoodLogEntry.objects.filter(user=user, date=day).select_related('product').defer('product__raw_data')) totals = {name: sum((getattr(entry, name) or ZERO for entry in entries), ZERO) for name in ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g')} meals = [] diff --git a/main/food/static/food/food.css b/main/food/static/food/food.css index 1cb6e87..20b95a8 100644 --- a/main/food/static/food/food.css +++ b/main/food/static/food/food.css @@ -2,3 +2,6 @@ .food-product-image{display:block;max-width:180px;max-height:180px;object-fit:contain;background:#fff;border-radius:1rem;margin:0 auto 1rem} .food-tabs,.food-actions{display:flex;gap:.5rem;flex-wrap:wrap;margin:1rem 0}.food-tabs a{padding:.55rem .9rem;border-radius:2rem;border:1px solid currentColor;text-decoration:none}.food-tabs a[aria-current=page]{background:#62bd70;color:#111;border-color:#62bd70}.food-product-list a,.food-result-button{display:flex;align-items:center;gap:.8rem;width:100%;text-align:left}.food-product-list img{width:58px;height:58px;object-fit:contain;background:#fff;border-radius:.6rem}.food-product-list strong,.food-product-list small{display:block}.food-result-button{border:0;background:none;color:inherit;font:inherit;cursor:pointer;min-height:44px}.food-barcode-form{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap;margin:1rem 0}.food-barcode-form input{min-width:130px;flex:1}.food-attribution{font-size:.85rem;opacity:.8} .food-scanner{max-width:620px;margin:1.5rem auto 6rem}.food-scanner-header{display:flex;align-items:center;gap:1rem}.food-scanner-header a{display:grid;place-items:center;min-width:44px;min-height:44px;font-size:2rem;text-decoration:none}.food-camera-frame{position:relative;aspect-ratio:4/3;background:#111;border-radius:1rem;overflow:hidden}.food-camera-frame video{width:100%;height:100%;object-fit:cover}.food-scan-guide{position:absolute;inset:25% 10%;border:3px solid #62bd70;border-radius:.8rem;pointer-events:none}.food-mobile-switch{display:none}@media(max-width:760px){.food-mobile-switch{position:fixed;bottom:env(safe-area-inset-bottom,0px);left:50%;transform:translateX(-50%);display:flex;gap:.3rem;background:#222;color:#fff;padding:.35rem;border-radius:2rem;z-index:20;box-shadow:0 2px 15px #0008}.food-mobile-switch a,.food-mobile-switch span{display:grid;place-items:center;min-width:110px;min-height:44px;padding:.2rem 1rem;border-radius:2rem;color:inherit;text-decoration:none}.food-mobile-switch [aria-current=page]{background:#555}} +.food-detail-title{display:flex;align-items:center;justify-content:space-between;gap:1rem}.food-favourite-form{flex:none}.food-favourite{min-width:44px;min-height:44px;border:0;background:none;color:#62bd70;font-size:2rem;cursor:pointer}.food-product-list li{display:flex;align-items:center;justify-content:space-between;gap:.5rem}.food-product-list li>a{flex:1;min-width:0}.food-product-list li>.food-favourite-form{margin:0} +/* V1 polish: keep the date and search titles from crowding the useful content. */ +.food-heading{align-items:end;margin-bottom:1.1rem}.food-heading h1{font-size:clamp(2rem,3.2vw,3.2rem);line-height:1.08;margin:.25rem 0 0}.food-heading nav a:nth-child(2){border-radius:999px;padding:0 1rem}.food-form-page h1{font-size:clamp(2.3rem,4vw,3.8rem);line-height:1.05;margin:.45rem 0 1rem;overflow-wrap:anywhere}.food-product-list li>a{text-decoration:none}.food-product-list li>a:hover strong,.food-product-list li>a:focus-visible strong{text-decoration:underline}.food-list-empty{border-style:dashed!important;opacity:.72}.food-entry>a{min-width:44px;min-height:44px;display:grid;place-items:center}.food-entry-main strong{overflow-wrap:anywhere}.food-export{margin-top:1.25rem}.food-export p{margin:.3rem 0 1rem;opacity:.75}.food-export-actions{display:flex;gap:.6rem;flex-wrap:wrap}.food-export-actions a{display:inline-flex;align-items:center;min-height:44px;padding:.55rem .8rem;border:1px solid currentColor;border-radius:999px;text-decoration:none}.food-export-actions a:hover,.food-export-actions a:focus-visible{background:#62bd7028}.food-entry-form{display:grid;gap:1rem}.food-entry-form [data-food-custom-fields],.food-entry-form [data-food-save-fields]{display:grid;gap:1rem}.food-entry-form .settings-switch-row{margin:.25rem 0}.food-edit-nutrition p{line-height:1.55}.food-edit-nutrition details{margin-top:.7rem}.food-entry-form .settings-switch input[type=checkbox]{min-height:0;padding:0;border:0;border-radius:0}.food-entry-form .settings-switch__copy strong{font-weight:700}.food-form-page .food-card .form-field label{line-height:1.35}@media(max-width:760px){.food-heading{align-items:start}.food-heading nav{flex:none}.food-heading nav a:nth-child(2){padding:0 .6rem}.food-heading h1{font-size:clamp(1.55rem,6vw,2.2rem)}.food-export{margin-top:.5rem}} diff --git a/main/food/static/food/portions.js b/main/food/static/food/portions.js new file mode 100644 index 0000000..0d49ac7 --- /dev/null +++ b/main/food/static/food/portions.js @@ -0,0 +1,19 @@ +(() => { + const select = document.querySelector('[data-food-portion-choice]'); + if (!select) return; + const amount = document.querySelector('#id_amount'); + const custom = document.querySelector('[data-food-custom-fields]'); + const amountField = document.querySelector('[data-food-amount-field]'); + const save = document.querySelector('#id_save_portion'); + const saveFields = document.querySelector('[data-food-save-fields]'); + const sync = () => { + const customSelected = select.value === 'custom'; + custom.hidden = !customSelected; + amountField.hidden = !customSelected; + if (!customSelected) amount.value = select.selectedOptions[0].dataset.amount || '100'; + saveFields.hidden = !customSelected || !save.checked; + }; + select.addEventListener('change', sync); + save.addEventListener('change', sync); + sync(); +})(); diff --git a/main/food/templates/food/add.html b/main/food/templates/food/add.html index 7529dd5..204196b 100644 --- a/main/food/templates/food/add.html +++ b/main/food/templates/food/add.html @@ -2,50 +2,5 @@ {% block title %}Add food · Tasknest{% endblock %} {% block content %} -
- ← Back to diary -

Add food

- {% if product %} -
- {% if product.image_url %}{% endif %} -

{{ product.product_name }}

- {% if product.brand %}

{{ product.brand }}

{% endif %} -

Per 100 {{ product.base_unit }}: {% if product.energy_kcal_100 is not None %}{{ product.energy_kcal_100|floatformat:0 }} kcal{% else %}— kcal{% endif %}

-
Nutrition information
-
Carbohydrates
{{ product.carbohydrates_100|default_if_none:'—' }} g
-
Protein
{{ product.protein_100|default_if_none:'—' }} g
-
Fat
{{ product.fat_100|default_if_none:'—' }} g
-
Sugars
{{ product.sugars_100|default_if_none:'—' }} g
-
Fibre
{{ product.fibre_100|default_if_none:'—' }} g
-
Salt
{{ product.salt_100|default_if_none:'—' }} g
-
- {% if product.source == 'openfoodfacts' %}

Product data from Open Food Facts.

{% endif %} -
-
- {% csrf_token %} - {% for field in form %}
{{ field.label_tag }}{{ field }}{{ field.errors }}
{% endfor %} - -
- {% else %} - - - - -
{% csrf_token %}
-

External product data from Open Food Facts.

- {% endif %} -
-{% if not product %}{% endif %} +{% include 'food/partials/add_content.html' %} {% endblock %} diff --git a/main/food/templates/food/edit.html b/main/food/templates/food/edit.html index 5c564eb..164d502 100644 --- a/main/food/templates/food/edit.html +++ b/main/food/templates/food/edit.html @@ -1,3 +1,6 @@ {% extends 'planner/base.html' %}{% load static %} {% block title %}Edit food log · Tasknest{% endblock %} -{% block content %}
← Back to diary

{{ entry.product_name_snapshot }}

{% if entry.brand_snapshot %}

{{ entry.brand_snapshot }}

{% endif %}

{% if entry.calories_kcal is not None %}{{ entry.calories_kcal|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {{ entry.carbohydrates_g|default_if_none:'—' }} g carbs · {{ entry.protein_g|default_if_none:'—' }} g protein · {{ entry.fat_g|default_if_none:'—' }} g fat

Nutrition information
Fibre
{{ entry.fibre_g|default_if_none:'—' }} g
Sugars
{{ entry.sugars_g|default_if_none:'—' }} g
Salt
{{ entry.salt_g|default_if_none:'—' }} g
{% csrf_token %}{% for field in form %}
{{ field.label_tag }}{{ field }}{{ field.errors }}
{% endfor %}
{% csrf_token %}
{% endblock %} +{% block content %} + +{% include 'food/partials/edit_content.html' %} +{% endblock %} diff --git a/main/food/templates/food/manual.html b/main/food/templates/food/manual.html index 2f197ca..a31143b 100644 --- a/main/food/templates/food/manual.html +++ b/main/food/templates/food/manual.html @@ -1,3 +1,3 @@ {% extends 'planner/base.html' %}{% load static %} {% block title %}Create food · Tasknest{% endblock %} -{% block content %}
← Back to foods

Create a food

Enter nutrition per 100 g or 100 ml. Missing optional values stay unknown.

{% csrf_token %}{% for field in form %}
{{ field.label_tag }}{{ field }}{{ field.errors }}
{% endfor %}
{% endblock %} +{% block content %}
← Back to foods

Create a food

Enter nutrition for the base quantity and unit you choose. Missing optional values stay unknown.

{% csrf_token %}{% for field in form %}
{{ field.label_tag }}{{ field }}{{ field.errors }}
{% endfor %}
{% endblock %} diff --git a/main/food/templates/food/partials/add_content.html b/main/food/templates/food/partials/add_content.html new file mode 100644 index 0000000..bc3fab5 --- /dev/null +++ b/main/food/templates/food/partials/add_content.html @@ -0,0 +1,49 @@ +{% load static %} +
+ ← Back to diary +

Add food

+ {% if product %} +
+ {% if product.image_url %}{% endif %} +

{{ product.product_name }}

{% include "food/partials/favourite_button.html" with is_favourite=product.is_favourite %}
+ {% if product.brand %}

{{ product.brand }}

{% endif %} +

Per 100 {{ product.base_unit }}: {% if product.energy_kcal_100 is not None %}{{ product.energy_kcal_100|floatformat:0 }} kcal{% else %}— kcal{% endif %}

+
Nutrition information
+
Carbohydrates
{{ product.carbohydrates_100|default_if_none:'—' }} g
+
Protein
{{ product.protein_100|default_if_none:'—' }} g
+
Fat
{{ product.fat_100|default_if_none:'—' }} g
+
Sugars
{{ product.sugars_100|default_if_none:'—' }} g
+
Fibre
{{ product.fibre_100|default_if_none:'—' }} g
+
Salt
{{ product.salt_100|default_if_none:'—' }} g
+
+ {% if product.source == 'openfoodfacts' %}

Product data from Open Food Facts.

{% endif %} +
+
+ {% csrf_token %} + {% include 'food/partials/portion_fields.html' %} + +
+ {% else %} + + + {% if tab == 'overview' and not query %} +

Favourites

{% include 'food/partials/product_list.html' with products=favourites %}
+

Recent

{% include 'food/partials/product_list.html' with products=recents %}
+ {% else %}{% include 'food/partials/product_list.html' with products=products %}{% endif %} + +
{% csrf_token %}
+

External product data from Open Food Facts.

+ {% endif %} +
+{% if product %}{% endif %} +{% if not product %}{% endif %} diff --git a/main/food/templates/food/partials/diary_content.html b/main/food/templates/food/partials/diary_content.html index 5dc1cc5..efdf029 100644 --- a/main/food/templates/food/partials/diary_content.html +++ b/main/food/templates/food/partials/diary_content.html @@ -13,6 +13,7 @@ diff --git a/main/food/templates/food/partials/edit_content.html b/main/food/templates/food/partials/edit_content.html new file mode 100644 index 0000000..98f350d --- /dev/null +++ b/main/food/templates/food/partials/edit_content.html @@ -0,0 +1,15 @@ +{% load static %} +
+ ← Back to diary +

{{ entry.product_name_snapshot }}

+ {% if entry.brand_snapshot %}

{{ entry.brand_snapshot }}

{% endif %} +

{% if entry.calories_kcal is not None %}{{ entry.calories_kcal|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {% if entry.carbohydrates_g is not None %}{{ entry.carbohydrates_g|floatformat:-1 }}{% else %}—{% endif %} g carbs · {% if entry.protein_g is not None %}{{ entry.protein_g|floatformat:-1 }}{% else %}—{% endif %} g protein · {% if entry.fat_g is not None %}{{ entry.fat_g|floatformat:-1 }}{% else %}—{% endif %} g fat

+
Nutrition information
Fibre
{{ entry.fibre_g|default_if_none:'—' }} g
Sugars
{{ entry.sugars_g|default_if_none:'—' }} g
Salt
{{ entry.salt_g|default_if_none:'—' }} g
+
+
{% csrf_token %} + {% include 'food/partials/portion_fields.html' %} + +
+
{% csrf_token %}
+
+{% if product %}{% endif %} diff --git a/main/food/templates/food/partials/favourite_button.html b/main/food/templates/food/partials/favourite_button.html new file mode 100644 index 0000000..279ea32 --- /dev/null +++ b/main/food/templates/food/partials/favourite_button.html @@ -0,0 +1,4 @@ +
+ {% csrf_token %} + +
diff --git a/main/food/templates/food/partials/favourite_update.html b/main/food/templates/food/partials/favourite_update.html new file mode 100644 index 0000000..8349dba --- /dev/null +++ b/main/food/templates/food/partials/favourite_update.html @@ -0,0 +1,3 @@ +{% include 'food/partials/favourite_button.html' %} +

Favourites

{% include 'food/partials/product_list.html' with products=favourites %}
+

Recent

{% include 'food/partials/product_list.html' with products=recents %}
diff --git a/main/food/templates/food/partials/portion_fields.html b/main/food/templates/food/partials/portion_fields.html new file mode 100644 index 0000000..4fbc54b --- /dev/null +++ b/main/food/templates/food/partials/portion_fields.html @@ -0,0 +1,15 @@ +
{{ form.meal.label_tag }}{{ form.meal }}{{ form.meal.errors }}
+{% if product %} +
{{ form.portion.errors }}
+
{{ form.amount.label_tag }}{{ form.amount }}{{ form.amount.errors }}{{ product.base_unit }}
+
{{ form.portion_label_snapshot.label_tag }}{{ form.portion_label_snapshot }}{{ form.portion_label_snapshot.errors }}
+
{{ form.save_portion.errors }}
+
{{ form.new_portion_label.label_tag }}{{ form.new_portion_label }}{{ form.new_portion_label.errors }}
+
{{ form.make_default.errors }}
+
+
+{% else %} +
{{ form.amount.label_tag }}{{ form.amount }}{{ form.amount.errors }}
+
{{ form.unit.label_tag }}{{ form.unit }}{{ form.unit.errors }}
+
{{ form.portion_label_snapshot.label_tag }}{{ form.portion_label_snapshot }}{{ form.portion_label_snapshot.errors }}
+{% endif %} diff --git a/main/food/templates/food/partials/product_list.html b/main/food/templates/food/partials/product_list.html new file mode 100644 index 0000000..8db6b25 --- /dev/null +++ b/main/food/templates/food/partials/product_list.html @@ -0,0 +1,5 @@ + diff --git a/main/food/test_csv_export.py b/main/food/test_csv_export.py new file mode 100644 index 0000000..9f04864 --- /dev/null +++ b/main/food/test_csv_export.py @@ -0,0 +1,74 @@ +import csv +from datetime import date, time +from decimal import Decimal +from io import StringIO +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.test import TestCase +from django.urls import reverse + +from .models import FoodLogEntry, FoodProduct, MealType, Unit +from .services.diary import diary_context +from planner.models import UserSettings + + +class FoodExportTests(TestCase): + def setUp(self): + self.user = get_user_model().objects.create_user(username='csv-user', password='test-password') + self.other = get_user_model().objects.create_user(username='other-csv-user', password='test-password') + self.client.force_login(self.user) + self.product = FoodProduct.objects.create(owner=self.user, product_name='Changed later') + + def entry(self, user, day, name, **values): + return FoodLogEntry.objects.create(user=user, date=day, time=time(8, 42), meal=MealType.BREAKFAST, + product_name_snapshot=name, brand_snapshot='Lidl', barcode_snapshot='1234567890123', + portion_label_snapshot='My bowl', amount=Decimal('300'), unit=Unit.GRAM, + calories_kcal=Decimal('174'), carbohydrates_g=Decimal('12'), protein_g=Decimal('18'), + fat_g=Decimal('6'), source=FoodProduct.Source.MANUAL, **values) + + def rows(self, period): + response = self.client.get(reverse('food:export', args=[period])) + self.assertEqual(response.status_code, 200) + self.assertTrue(response.streaming) + body = b''.join(response.streaming_content).decode('utf-8') + return response, list(csv.DictReader(StringIO(body))) + + @patch('food.views.localdate_for_user', return_value=date(2026, 10, 3)) + def test_week_is_monday_sunday_user_scoped_and_snapshot_based(self, today): + self.entry(self.user, date(2026, 9, 28), 'Monday food') + self.entry(self.user, date(2026, 10, 3), '=Snapshot food') + self.entry(self.user, date(2026, 10, 4), 'Sunday food') + self.entry(self.user, date(2026, 9, 27), 'Outside week') + self.entry(self.other, date(2026, 10, 3), 'Private food') + response, rows = self.rows('week') + self.assertIn('food-2026-W40.csv', response['Content-Disposition']) + self.assertEqual([row['date'] for row in rows], ['2026-09-28', '2026-10-03', '2026-10-04']) + self.assertEqual(rows[1]['product_name'], "'=Snapshot food") + self.assertEqual(rows[1]['portion_label'], 'My bowl') + self.assertEqual(rows[1]['calories_kcal'], '174') + self.assertEqual(rows[1]['fibre_g'], '') + self.assertEqual(rows[1]['time'], '08:42:00') + + @patch('food.views.localdate_for_user', return_value=date(2026, 10, 3)) + def test_month_includes_only_calendar_month(self, today): + self.entry(self.user, date(2026, 9, 30), 'September') + self.entry(self.user, date(2026, 10, 1), 'October first') + self.entry(self.user, date(2026, 10, 31), 'October last') + response, rows = self.rows('month') + self.assertIn('food-2026-10.csv', response['Content-Disposition']) + self.assertEqual([row['product_name'] for row in rows], ['October first', 'October last']) + + def test_export_requires_login_and_rejects_other_periods(self): + self.assertEqual(self.client.get(reverse('food:export', args=['year'])).status_code, 404) + self.client.logout() + self.assertEqual(self.client.get(reverse('food:export', args=['week'])).status_code, 302) + + def test_diary_uses_bounded_queries_for_multiple_rows(self): + UserSettings.objects.create(user=self.user) + for index in range(8): + FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.LUNCH, + product=self.product, product_name_snapshot=f'Food {index}', amount=100, unit=Unit.GRAM) + with self.assertNumQueries(2): + context = diary_context(self.user, date(2026, 10, 3)) + self.assertEqual(len(context['meals'][1]['entries']), 8) diff --git a/main/food/test_repeat_logging.py b/main/food/test_repeat_logging.py new file mode 100644 index 0000000..5cd6cb5 --- /dev/null +++ b/main/food/test_repeat_logging.py @@ -0,0 +1,120 @@ +from datetime import date +from decimal import Decimal + +from django.contrib.auth import get_user_model +from django.test import TestCase +from django.urls import reverse + +from .models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit + + +class RepeatLoggingTests(TestCase): + def setUp(self): + self.user = get_user_model().objects.create_user(username='repeat-one', password='test-password') + self.other = get_user_model().objects.create_user(username='repeat-two', password='test-password') + self.client.force_login(self.user) + self.product = FoodProduct.objects.create(owner=self.user, product_name='Greek yoghurt', + base_unit=Unit.GRAM, energy_kcal_100=Decimal('58'), protein_100=Decimal('6')) + + def test_favourite_toggle_is_user_specific_and_htmx_updates(self): + url = reverse('food:toggle-favourite', args=[self.product.pk]) + payload = {'date': '2026-10-03', 'meal': 'breakfast', 'tab': 'favourites', 'is_list': '1'} + response = self.client.post(url, payload, HTTP_HX_REQUEST='true') + self.assertContains(response, 'aria-pressed="true"') + self.assertTrue(FoodFavourite.objects.filter(user=self.user, product=self.product).exists()) + self.assertFalse(FoodFavourite.objects.filter(user=self.other, product=self.product).exists()) + response = self.client.post(url, payload, HTTP_HX_REQUEST='true') + self.assertEqual(response.content, b'') + self.client.force_login(self.other) + self.assertEqual(self.client.post(url, payload).status_code, 404) + + def test_recent_products_are_unique_and_ordered_by_last_use(self): + other_product = FoodProduct.objects.create(owner=self.user, product_name='Soup') + for product in (self.product, other_product, self.product): + FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.LUNCH, + product=product, product_name_snapshot=product.product_name, amount=100, unit=Unit.GRAM) + response = self.client.get(reverse('food:add'), {'tab': 'recent'}) + self.assertEqual(response.status_code, 200) + html = response.content.decode() + self.assertEqual(html.count('Greek yoghurt'), 1) + self.assertLess(html.index('Greek yoghurt'), html.index('Soup')) + + def test_custom_portion_calculation_and_snapshot(self): + portion = FoodPortion.objects.create(user=self.user, product=self.product, + label='My bowl', amount=Decimal('300'), unit=Unit.GRAM, is_default=True) + response = self.client.get(reverse('food:add'), {'product': self.product.pk, 'meal': 'breakfast'}) + self.assertContains(response, 'My bowl') + self.assertContains(response, 'value="portion:%s"' % portion.pk) + response = self.client.post(reverse('food:add'), {'date': '2026-10-03', 'product': self.product.pk, + 'meal': 'breakfast', 'amount': '100', 'unit': 'g', 'portion': f'portion:{portion.pk}'}) + self.assertEqual(response.status_code, 302) + entry = FoodLogEntry.objects.get(user=self.user) + self.assertEqual(entry.amount, Decimal('300')) + self.assertEqual(entry.calories_kcal, Decimal('174')) + self.assertEqual(entry.protein_g, Decimal('18')) + self.assertEqual(entry.portion_label_snapshot, 'My bowl') + portion.label = 'Renamed bowl' + portion.save() + entry.refresh_from_db() + self.assertEqual(entry.portion_label_snapshot, 'My bowl') + + def test_save_new_default_portion(self): + old = FoodPortion.objects.create(user=self.user, product=self.product, + label='Old bowl', amount=Decimal('200'), unit=Unit.GRAM, is_default=True) + response = self.client.post(reverse('food:add'), {'date': '2026-10-03', 'product': self.product.pk, + 'meal': 'breakfast', 'amount': '250', 'unit': 'g', 'portion': 'custom', + 'save_portion': 'on', 'new_portion_label': 'New bowl', 'make_default': 'on'}) + self.assertEqual(response.status_code, 302) + old.refresh_from_db() + self.assertFalse(old.is_default) + new = FoodPortion.objects.get(user=self.user, product=self.product, label='New bowl') + self.assertTrue(new.is_default) + self.assertEqual(new.amount, Decimal('250')) + self.assertEqual(FoodLogEntry.objects.get(user=self.user).portion_label_snapshot, 'New bowl') + + def test_manual_food_basis_and_optional_nutrients(self): + response = self.client.post(reverse('food:manual'), {'date': '2026-10-03', 'meal': 'dinner', + 'product_name': 'Homemade soup', 'brand': '', 'barcode': '', 'basis_amount': '250', + 'base_unit': 'ml', 'energy_kcal_100': '150', 'carbohydrates_100': '20', + 'protein_100': '5', 'fat_100': '2'}) + self.assertEqual(response.status_code, 302) + product = FoodProduct.objects.get(owner=self.user, product_name='Homemade soup') + self.assertEqual(product.source, FoodProduct.Source.MANUAL) + self.assertEqual(product.energy_kcal_100, Decimal('60')) + self.assertEqual(product.carbohydrates_100, Decimal('8')) + self.assertIsNone(product.fibre_100) + response = self.client.post(reverse('food:add'), {'date': '2026-10-03', 'product': product.pk, + 'meal': 'dinner', 'amount': '250', 'unit': 'ml', 'portion': 'custom'}) + self.assertEqual(response.status_code, 302) + entry = FoodLogEntry.objects.get(user=self.user) + self.assertEqual(entry.calories_kcal, Decimal('150')) + self.assertIsNone(entry.fibre_g) + + def test_cannot_use_another_users_portion(self): + other_product = FoodProduct.objects.create(owner=self.other, product_name='Private') + other_portion = FoodPortion.objects.create(user=self.other, product=other_product, + label='Private bowl', amount=300, unit=Unit.GRAM) + response = self.client.post(reverse('food:add'), {'date': '2026-10-03', 'product': self.product.pk, + 'meal': 'breakfast', 'amount': '100', 'unit': 'g', 'portion': f'portion:{other_portion.pk}'}) + self.assertEqual(response.status_code, 200) + self.assertFalse(FoodLogEntry.objects.filter(user=self.user).exists()) + + def test_local_search_ranks_exact_and_favourites_first(self): + favourite = FoodProduct.objects.create(owner=self.user, product_name='Greek yoghurt vanilla') + ordinary = FoodProduct.objects.create(owner=self.user, product_name='Vanilla Greek yoghurt') + FoodFavourite.objects.create(user=self.user, product=favourite) + response = self.client.get(reverse('food:add'), {'q': 'Greek yoghurt'}) + html = response.content.decode() + self.assertLess(html.index('Greek yoghurt'), + html.index('Greek yoghurt vanilla')) + self.assertLess(html.index('Greek yoghurt vanilla'), + html.index('Vanilla Greek yoghurt')) + + def test_invalid_custom_portion_stays_on_form_with_htmx(self): + response = self.client.post(reverse('food:add'), {'date': '2026-10-03', 'product': self.product.pk, + 'meal': 'breakfast', 'amount': '250', 'unit': 'g', 'portion': 'custom', + 'save_portion': 'on'}, HTTP_HX_REQUEST='true') + self.assertContains(response, 'Enter a label for the saved portion') + self.assertContains(response, 'id="food-workspace"') + self.assertNotContains(response, '') + self.assertNotIn('HX-Push-Url', response) diff --git a/main/food/urls.py b/main/food/urls.py index 1b7c584..639220b 100644 --- a/main/food/urls.py +++ b/main/food/urls.py @@ -14,4 +14,6 @@ urlpatterns = [ path('manual/', views.manual_food, name='manual'), path('log//', views.edit_entry, name='edit'), path('log//delete/', views.delete_entry, name='delete'), + path('product//favourite/', views.toggle_favourite, name='toggle-favourite'), + path('export//', views.export_csv, name='export'), ] diff --git a/main/food/views.py b/main/food/views.py index 1576603..63a7a9d 100644 --- a/main/food/views.py +++ b/main/food/views.py @@ -1,25 +1,84 @@ from decimal import Decimal +import calendar +import csv +from datetime import date, timedelta import logging import re from urllib.parse import urlencode from django.contrib.auth.decorators import login_required -from django.http import HttpResponseBadRequest +from django.http import Http404, HttpResponse, HttpResponseBadRequest, StreamingHttpResponse from django.contrib import messages from django.db.models import Q from django.db.models import Max +from django.db import transaction from django.shortcuts import get_object_or_404, redirect, render from django.urls import reverse from django.views.decorators.http import require_http_methods, require_POST from .forms import FoodLogForm, ManualFoodForm -from .models import FoodLogEntry, FoodProduct, MealType +from .models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType from .services.diary import diary_context, selected_date from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search +from planner.timezones import localdate_for_user logger = logging.getLogger(__name__) +EXPORT_FIELDS = ( + 'date', 'time', 'meal', 'product_name_snapshot', 'brand_snapshot', 'barcode_snapshot', + 'portion_label_snapshot', 'amount', 'unit', 'calories_kcal', 'carbohydrates_g', + 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g', 'source', +) +EXPORT_HEADERS = ( + 'date', 'time', 'meal', 'product_name', 'brand', 'barcode', 'portion_label', + 'amount', 'unit', 'calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', + 'fibre_g', 'sugars_g', 'salt_g', 'source', +) + + +class _CsvSink: + def write(self, value): + return value + + +def _csv_value(value): + if value is None: + return '' + if isinstance(value, Decimal): + return format(value.normalize(), 'f') + if isinstance(value, str) and value.lstrip().startswith(('=', '+', '-', '@')): + return "'" + value + return str(value) + + +@login_required +def export_csv(request, period): + today = localdate_for_user(request.user) + if period == 'week': + first = today - timedelta(days=today.weekday()) + last = first + timedelta(days=6) + iso_year, iso_week, _ = today.isocalendar() + filename = f'food-{iso_year}-W{iso_week:02d}.csv' + elif period == 'month': + first = today.replace(day=1) + last = today.replace(day=calendar.monthrange(today.year, today.month)[1]) + filename = f'food-{today:%Y-%m}.csv' + else: + raise Http404('Unknown export period.') + rows = (FoodLogEntry.objects.filter(user=request.user, date__range=(first, last)) + .order_by('date', 'time', 'pk').values_list(*EXPORT_FIELDS).iterator(chunk_size=500)) + writer = csv.writer(_CsvSink()) + + def output(): + yield writer.writerow(EXPORT_HEADERS) + for row in rows: + yield writer.writerow([_csv_value(value) for value in row]) + + response = StreamingHttpResponse(output(), content_type='text/csv; charset=utf-8') + response['Content-Disposition'] = f'attachment; filename="{filename}"' + return response + def _day(request): try: @@ -28,6 +87,34 @@ def _day(request): return None, HttpResponseBadRequest(str(error)) +def _portion_options(form, product): + if not product: + return [] + options = [] + for value, label in form.fields['portion'].choices: + amount = '' + if value == 'base': + amount = '100' + elif value == 'serving': + amount = str(product.serving_amount) + elif value.startswith('portion:'): + amount = str(form.portions[value.partition(':')[2]].amount) + options.append({'value': value, 'label': label, 'amount': amount}) + return options + + +def _save_custom_portion(form, user, product, entry): + if form.cleaned_data.get('portion') != 'custom' or not form.cleaned_data.get('save_portion'): + return + if form.cleaned_data.get('make_default'): + FoodPortion.objects.filter(user=user, product=product, is_default=True).update(is_default=False) + portion = FoodPortion(user=user, product=product, + label=form.cleaned_data['new_portion_label'].strip(), amount=entry.amount, + unit=entry.unit, is_default=form.cleaned_data.get('make_default', False)) + portion.full_clean() + portion.save() + + def _save_entry(form, user, day, product): entry = form.save(commit=False) entry.user = user @@ -47,12 +134,15 @@ def _save_entry(form, user, day, product): setattr(entry, target, (value * factor).quantize(Decimal('0.001')) if value is not None else None) entry.full_clean() entry.save() + _save_custom_portion(form, user, product, entry) return entry def _diary_response(request, day): if request.headers.get('HX-Request') == 'true': - return render(request, 'food/partials/diary_content.html', diary_context(request.user, day)) + response = render(request, 'food/partials/diary_content.html', diary_context(request.user, day)) + response['HX-Push-Url'] = f"{reverse('food:diary')}?date={day.isoformat()}" + return response return redirect(f"{reverse('food:diary')}?date={day.isoformat()}") @@ -76,27 +166,94 @@ def add_food(request): product_id = request.GET.get('product') or request.POST.get('product') product = get_object_or_404(FoodProduct, pk=product_id, owner=request.user) if product_id else None query = request.GET.get('q', '').strip()[:100] - tab = request.GET.get('tab', 'recent') - if tab not in ('recent', 'favourites', 'mine'): - tab = 'recent' + tab = request.GET.get('tab', 'overview') + if tab not in ('overview', 'recent', 'favourites', 'mine'): + tab = 'overview' products = FoodProduct.objects.filter(owner=request.user) + favourite_ids = set(FoodFavourite.objects.filter(user=request.user).values_list('product_id', flat=True)) + recent_ids = list(FoodLogEntry.objects.filter(user=request.user, product__isnull=False) + .values('product_id').annotate(last_used=Max('created_at')) + .order_by('-last_used').values_list('product_id', flat=True)[:30]) + recent_rank = {product_id: index for index, product_id in enumerate(recent_ids)} if query: - products = products.filter(Q(product_name__icontains=query) | Q(brand__icontains=query) | Q(barcode__icontains=query)) - if tab == 'favourites': - products = products.filter(favourites__user=request.user).order_by('product_name') + normalized = ' '.join(query.split()).casefold() + for token in normalized.split(): + products = products.filter(Q(product_name__icontains=token) | Q(brand__icontains=token) | Q(barcode__icontains=token)) + def rank(item): + name = ' '.join(item.product_name.split()).casefold() + return (0 if item.barcode == normalized else 1 if name == normalized else + 2 if item.pk in favourite_ids and name.startswith(normalized) else + 3 if item.pk in favourite_ids else 4 if item.pk in recent_rank else 5, + recent_rank.get(item.pk, 999), name) + products = sorted(products[:500], key=rank)[:40] + tab = 'mine' + elif tab == 'favourites': + products = list(products.filter(pk__in=favourite_ids).order_by('product_name')[:30]) elif tab == 'mine': - products = products.order_by('product_name') + products = list(products.order_by('product_name')[:40]) + elif tab == 'recent': + by_id = products.in_bulk(recent_ids) + products = [by_id[pk] for pk in recent_ids if pk in by_id] else: - products = products.filter(log_entries__user=request.user).annotate(last_used=Max('log_entries__created_at')).order_by('-last_used') + by_id = products.in_bulk(recent_ids) + favourites = list(products.filter(pk__in=favourite_ids).order_by('product_name')[:20]) + recents = [by_id[pk] for pk in recent_ids if pk in by_id and pk not in favourite_ids][:20] + products = favourites + recents + for item in products: + item.is_favourite = item.pk in favourite_ids + if product: + product.is_favourite = product.pk in favourite_ids form = FoodLogForm(request.POST or None, product=product, initial={'meal': meal, 'unit': product.base_unit if product else 'g'}) if product else None if request.method == 'POST': if not product: return HttpResponseBadRequest('Choose a product.') if form.is_valid(): - _save_entry(form, request.user, day, product) + with transaction.atomic(): + _save_entry(form, request.user, day, product) return _diary_response(request, day) - return render(request, 'food/add.html', {'day': day, 'meal': meal, 'products': products[:40], - 'product': product, 'form': form, 'query': query, 'tab': tab}) + portion_options = _portion_options(form, product) if form else [] + template = 'food/partials/add_content.html' if request.method == 'POST' and request.headers.get('HX-Request') == 'true' else 'food/add.html' + return render(request, template, {'day': day, 'meal': meal, 'products': products[:40], + 'product': product, 'form': form, 'query': query, 'tab': tab, + 'favourite_ids': favourite_ids, 'favourites': favourites if not query and tab == 'overview' else [], + 'recents': recents if not query and tab == 'overview' else [], + 'is_favourite': product.pk in favourite_ids if product else False, 'portion_options': portion_options}) + + +@login_required +@require_POST +def toggle_favourite(request, pk): + product = get_object_or_404(FoodProduct, pk=pk, owner=request.user) + favourite, created = FoodFavourite.objects.get_or_create(user=request.user, product=product) + if not created: + favourite.delete() + day, error = _day(request) + if error: + return error + meal = request.POST.get('meal') or MealType.BREAKFAST + if meal not in MealType.values: + return HttpResponseBadRequest('Invalid meal.') + if request.headers.get('HX-Request') == 'true': + if request.POST.get('tab') == 'overview' and request.POST.get('is_list') == '1': + favourite_ids = set(FoodFavourite.objects.filter(user=request.user).values_list('product_id', flat=True)) + recent_ids = list(FoodLogEntry.objects.filter(user=request.user, product__isnull=False) + .values('product_id').annotate(last_used=Max('created_at')) + .order_by('-last_used').values_list('product_id', flat=True)[:30]) + favourites = list(FoodProduct.objects.filter(owner=request.user, pk__in=favourite_ids).order_by('product_name')[:20]) + by_id = FoodProduct.objects.filter(owner=request.user).in_bulk(recent_ids) + recents = [by_id[pk] for pk in recent_ids if pk in by_id and pk not in favourite_ids][:20] + for item in favourites + recents: + item.is_favourite = item.pk in favourite_ids + return render(request, 'food/partials/favourite_update.html', { + 'product': product, 'is_favourite': created, 'day': day, 'meal': meal, + 'tab': 'overview', 'is_list': True, 'favourites': favourites, 'recents': recents, + }) + if request.POST.get('tab') == 'favourites' and request.POST.get('is_list') == '1' and not created: + return HttpResponse('') + return render(request, 'food/partials/favourite_button.html', {'product': product, + 'is_favourite': created, 'day': day, 'meal': meal, + 'tab': request.POST.get('tab'), 'is_list': request.POST.get('is_list') == '1'}) + return redirect(f"{reverse('food:add')}?date={day}&meal={meal}&product={product.pk}") @login_required @@ -180,7 +337,7 @@ def manual_food(request): barcode = request.GET.get('barcode', '').strip() if barcode and not re.fullmatch(r'[0-9]{1,64}', barcode): return HttpResponseBadRequest('Invalid barcode.') - form = ManualFoodForm(request.POST or None, initial={'barcode': barcode}) + form = ManualFoodForm(request.POST or None, user=request.user, initial={'barcode': barcode}) if request.method == 'POST' and form.is_valid(): product = form.save(commit=False) product.owner = request.user @@ -203,10 +360,15 @@ def edit_entry(request, pk): factor = updated.amount / original_amount for field, original in original_nutrients.items(): setattr(updated, field, (original * factor).quantize(Decimal('0.001')) if original is not None else None) - updated.full_clean() - updated.save() + with transaction.atomic(): + updated.full_clean() + updated.save() + if product: + _save_custom_portion(form, request.user, product, updated) return _diary_response(request, entry.date) - return render(request, 'food/edit.html', {'entry': entry, 'form': form}) + template = 'food/partials/edit_content.html' if request.method == 'POST' and request.headers.get('HX-Request') == 'true' else 'food/edit.html' + return render(request, template, {'entry': entry, 'form': form, 'product': product, + 'portion_options': _portion_options(form, product)}) @login_required