adding food logging, phase 2

This commit is contained in:
Joren de Graaf
2026-10-03 20:47:32 +02:00
parent 761cb180c5
commit fca2ef2acd
11 changed files with 294 additions and 12 deletions
+21 -1
View File
@@ -1,6 +1,6 @@
from django import forms from django import forms
from .models import FoodProduct, Unit from .models import FoodLogEntry, FoodProduct, MealType
class ManualFoodForm(forms.ModelForm): class ManualFoodForm(forms.ModelForm):
@@ -18,3 +18,23 @@ class ManualFoodForm(forms.ModelForm):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
for field in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100'): for field in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100'):
self.fields[field].required = True self.fields[field].required = True
class FoodLogForm(forms.ModelForm):
class Meta:
model = FoodLogEntry
fields = ('meal', 'amount', 'unit', 'portion_label_snapshot')
labels = {'portion_label_snapshot': 'Portion label (optional)'}
widgets = {'amount': forms.NumberInput(attrs={'min': '0.001', 'step': '0.001'})}
def __init__(self, *args, product=None, **kwargs):
super().__init__(*args, **kwargs)
self.product = product or getattr(self.instance, 'product', None)
if self.product and self.product.pk:
self.fields['unit'].initial = self.product.base_unit
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
+49
View File
@@ -0,0 +1,49 @@
from datetime import timedelta
from decimal import Decimal
from django.utils import timezone
from django.utils.dateparse import parse_date
from food.models import FoodLogEntry, MealType
from planner.models import UserSettings
from planner.timezones import localdate_for_user
ZERO = Decimal('0')
def selected_date(request):
value = request.GET.get('date') or request.POST.get('date')
if not value:
return localdate_for_user(request.user)
day = parse_date(value)
if day is None or day.isoformat() != value:
raise ValueError('Enter a valid date in YYYY-MM-DD format.')
return day
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'))
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 = []
for key, label in MealType.choices:
items = [entry for entry in entries if entry.meal == key]
meals.append({'key': key, 'label': label, 'entries': items,
'calories': sum((entry.calories_kcal or ZERO for entry in items), ZERO)})
macros = []
for label, name, goal, color in (
('Carbohydrates', 'carbohydrates_g', goals.carbohydrate_goal_g, 'pink'),
('Protein', 'protein_g', goals.protein_goal_g, 'blue'),
('Fat', 'fat_g', goals.fat_goal_g, 'orange'),
):
eaten = totals[name]
macros.append({'label': label, 'eaten': eaten, 'goal': goal, 'remaining': goal - eaten if goal is not None else None,
'percent': min(100, int(eaten * 100 / goal)) if goal else None, 'color': color})
calorie_goal = goals.daily_calorie_goal
calories = totals['calories_kcal']
return {'day': day, 'previous_day': day - timedelta(days=1), 'next_day': day + timedelta(days=1),
'meals': meals, 'totals': totals, 'macros': macros, 'calorie_goal': calorie_goal,
'calorie_remaining': Decimal(calorie_goal) - calories if calorie_goal is not None else None,
'calorie_percent': min(100, int(calories * 100 / calorie_goal)) if calorie_goal else 0}
+2
View File
@@ -0,0 +1,2 @@
.food-page{max-width:1180px;margin:0 auto;padding:1.5rem 0 4rem}.food-heading,.food-meal-heading{display:flex;justify-content:space-between;align-items:center;gap:1rem}.food-heading nav{display:flex;gap:.5rem;align-items:center}.food-heading nav a,.food-add-meal{display:inline-flex;align-items:center;justify-content:center;min-width:44px;min-height:44px;border:1px solid currentColor;border-radius:50%;text-decoration:none}.food-layout{display:grid;grid-template-columns:minmax(0,1fr) minmax(290px,340px);gap:2rem;align-items:start}.food-sidebar{position:sticky;top:1rem}.food-card{background:var(--surface,#222);border:1px solid var(--border,#555);border-radius:1.2rem;padding:1.2rem;margin-bottom:1rem}.food-card h2,.food-card h3{margin:.1rem 0 .5rem}.food-remaining{font-size:1.45rem;font-weight:700}.food-progress{height:.65rem;background:#7776;border-radius:2rem;overflow:hidden}.food-progress span{display:block;height:100%;background:#62bd70;border-radius:inherit}.food-macros{display:grid;gap:.7rem}.food-macro{display:flex;align-items:center;gap:1rem}.food-macro p{margin:.15rem 0}.food-ring{--accent:#d45b8b;flex:none;width:74px;height:74px;border-radius:50%;display:grid;place-items:center;background:conic-gradient(var(--accent) var(--progress,0%),#7776 0)}.food-ring span{display:grid;place-items:center;width:60px;height:60px;background:var(--surface,#222);border-radius:50%;font-weight:700}.food-macro--blue{--accent:#53a9e7}.food-macro--orange{--accent:#e87952}.food-meal{margin-bottom:1.5rem}.food-meal-heading h2{margin:0}.food-meal-heading p{margin:.1rem 0;color:#62bd70}.food-add-meal{color:#62bd70;font-size:1.8rem}.food-entry-list,.food-product-list{list-style:none;margin:.8rem 0;padding:0}.food-entry,.food-product-list li{background:var(--surface,#222);border:1px solid var(--border,#555);padding:1rem;border-radius:1rem;margin:.4rem 0}.food-entry{display:flex;align-items:center;justify-content:space-between;gap:1rem}.food-entry-main{display:flex;align-items:center;gap:.8rem;min-width:0}.food-entry-main img{width:64px;height:64px;object-fit:contain;background:white;border-radius:.6rem}.food-entry-main strong,.food-entry-main span,.food-entry-main small{display:block}.food-entry-main small,.food-entry-main span,.food-empty{opacity:.75}.food-form-page{max-width:620px;margin:1.5rem auto 4rem}.food-form-page .food-card{margin-top:1rem}.food-search{display:flex;flex-wrap:wrap;gap:.6rem;align-items:center}.food-search input{min-width:180px;flex:1}.food-product-list a{display:block;min-height:44px;align-content:center}.food-form-page details dl{display:grid;grid-template-columns:1fr 1fr;gap:.4rem}.food-form-page details dd{margin:0;text-align:right}@media(max-width:760px){.food-layout{display:flex;flex-direction:column-reverse;gap:1rem}.food-sidebar{position:static;width:100%}.food-macros{grid-template-columns:repeat(3,minmax(0,1fr));gap:.4rem}.food-macro{display:block;padding:.65rem;text-align:center}.food-ring{margin:auto;width:58px;height:58px}.food-ring span{width:46px;height:46px;font-size:.8rem}.food-macro h3{font-size:.9rem;overflow-wrap:anywhere}.food-macro p{font-size:.8rem}.food-heading h1{font-size:1.5rem}.food-page{padding-top:.5rem}}@media(max-width:400px){.food-macros{grid-template-columns:1fr}.food-macro{display:flex;text-align:left}.food-ring{margin:0}}@media(prefers-reduced-motion:reduce){.food-page *{scroll-behavior:auto!important;animation:none!important;transition:none!important}}
.food-product-image{display:block;max-width:180px;max-height:180px;object-fit:contain;background:#fff;border-radius:1rem;margin:0 auto 1rem}
+3
View File
@@ -0,0 +1,3 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Add food · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}"><div id="food-workspace" class="food-form-page"><a href="{% url 'food:diary' %}?date={{ day|date:'Y-m-d' }}">← Back to diary</a><h1>Add food</h1>{% if product %}<section class="food-card">{% if product.image_url %}<img class="food-product-image" src="{{ product.image_url }}" alt="" loading="lazy">{% endif %}<h2>{{ product.product_name }}</h2>{% if product.brand %}<p>{{ product.brand }}</p>{% endif %}<p>Per 100 {{ product.base_unit }}: {% if product.energy_kcal_100 is not None %}{{ product.energy_kcal_100|floatformat:0 }} kcal{% else %}— kcal{% endif %}</p><details><summary>Nutrition information</summary><dl><dt>Carbohydrates</dt><dd>{{ product.carbohydrates_100|default_if_none:'—' }} g</dd><dt>Protein</dt><dd>{{ product.protein_100|default_if_none:'—' }} g</dd><dt>Fat</dt><dd>{{ product.fat_100|default_if_none:'—' }} g</dd><dt>Sugars</dt><dd>{{ product.sugars_100|default_if_none:'—' }} g</dd><dt>Fibre</dt><dd>{{ product.fibre_100|default_if_none:'—' }} g</dd><dt>Salt</dt><dd>{{ product.salt_100|default_if_none:'—' }} g</dd></dl></details></section><form method="post" class="food-card" hx-post="{% url 'food:add' %}" hx-target="#food-workspace" hx-push-url="{% url 'food:diary' %}?date={{ day|date:'Y-m-d' }}" hx-swap="outerHTML">{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="product" value="{{ product.pk }}">{% for field in form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Log food</button></form>{% else %}<form method="get" class="food-search"><input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}"><label for="food-query">Search your foods</label><input id="food-query" name="q" value="{{ query }}" type="search"><button class="button" type="submit">Search</button></form><ul class="food-product-list">{% for item in products %}<li><a href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}&amp;product={{ item.pk }}">{{ item.product_name }}{% if item.brand %} · {{ item.brand }}{% endif %}</a></li>{% empty %}<li>No local foods yet.</li>{% endfor %}</ul><a class="button" href="{% url 'food:manual' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">Create a food manually</a>{% endif %}</div>{% endblock %}
+3 -9
View File
@@ -1,13 +1,7 @@
{% extends 'planner/base.html' %} {% extends 'planner/base.html' %}
{% load static %}
{% block title %}Food · Tasknest{% endblock %} {% block title %}Food · Tasknest{% endblock %}
{% block content %} {% block content %}
<section class="planner-hero" aria-labelledby="food-heading"> <link rel="stylesheet" href="{% static 'food/food.css' %}">
<div> {% include 'food/partials/diary_content.html' %}
<p class="eyebrow">Food</p>
<h1 id="food-heading">Food diary</h1>
<p>Food logging is coming soon.</p>
</div>
</section>
{% endblock %} {% endblock %}
+3
View File
@@ -0,0 +1,3 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Edit food log · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}"><div id="food-workspace" class="food-form-page"><a href="{% url 'food:diary' %}?date={{ entry.date|date:'Y-m-d' }}">← Back to diary</a><h1>{{ entry.product_name_snapshot }}</h1>{% if entry.brand_snapshot %}<p>{{ entry.brand_snapshot }}</p>{% endif %}<div class="food-card"><p>{% 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</p><details><summary>Nutrition information</summary><dl><dt>Fibre</dt><dd>{{ entry.fibre_g|default_if_none:'—' }} g</dd><dt>Sugars</dt><dd>{{ entry.sugars_g|default_if_none:'—' }} g</dd><dt>Salt</dt><dd>{{ entry.salt_g|default_if_none:'—' }} g</dd></dl></details></div><form method="post" class="food-card" hx-post="{% url 'food:edit' entry.pk %}" hx-target="#food-workspace" hx-swap="outerHTML" hx-push-url="{% url 'food:diary' %}?date={{ entry.date|date:'Y-m-d' }}">{% csrf_token %}{% for field in form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save changes</button></form><form method="post" action="{% url 'food:delete' entry.pk %}" onsubmit="return confirm('Delete this food entry?')" hx-post="{% url 'food:delete' entry.pk %}" hx-target="#food-workspace" hx-swap="outerHTML" hx-push-url="{% url 'food:diary' %}?date={{ entry.date|date:'Y-m-d' }}">{% csrf_token %}<button type="submit" class="button button--secondary">Delete entry</button></form></div>{% endblock %}
+3
View File
@@ -0,0 +1,3 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Create food · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}"><div class="food-form-page"><a href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">← Back to foods</a><h1>Create a food</h1><p>Enter nutrition per 100 g or 100 ml. Missing optional values stay unknown.</p><form method="post" class="food-card">{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}">{% for field in form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save food</button></form></div>{% endblock %}
@@ -0,0 +1,19 @@
<div id="food-workspace" class="food-page"><div id="food-diary">
<header class="food-heading"><div><p class="eyebrow">Food diary</p><h1>{{ day|date:"l j F Y" }}</h1></div><nav aria-label="Diary dates"><a href="{% url 'food:diary' %}?date={{ previous_day|date:'Y-m-d' }}" aria-label="Previous day">←</a><a href="{% url 'food:diary' %}">Today</a><a href="{% url 'food:diary' %}?date={{ next_day|date:'Y-m-d' }}" aria-label="Next day">→</a></nav></header>
<div class="food-layout">
<div class="food-meals">
{% for meal in meals %}
<section class="food-meal" id="meal-{{ meal.key }}" aria-labelledby="meal-title-{{ meal.key }}">
<div class="food-meal-heading"><div><h2 id="meal-title-{{ meal.key }}">{{ meal.label }}</h2><p>{{ meal.calories|floatformat:0 }} kcal</p></div><a class="food-add-meal" href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal.key }}" aria-label="Add food to {{ meal.label }}">+</a></div>
{% if meal.entries %}<ul class="food-entry-list">{% for entry in meal.entries %}<li class="food-entry"><div class="food-entry-main">{% if entry.product and entry.product.image_url %}<img src="{{ entry.product.image_url }}" alt="" loading="lazy">{% endif %}<div><strong>{{ entry.product_name_snapshot }}</strong>{% if entry.brand_snapshot %}<span>{{ entry.brand_snapshot }}</span>{% endif %}<small>{% if entry.calories_kcal is not None %}{{ entry.calories_kcal|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {% if entry.portion_label_snapshot %}{{ entry.portion_label_snapshot }} {% endif %}({{ entry.amount|floatformat:-3 }} {{ entry.unit }})</small></div></div><a href="{% url 'food:edit' entry.pk %}" aria-label="Edit {{ entry.product_name_snapshot }}">Edit</a></li>{% endfor %}</ul>{% else %}<p class="food-empty">Nothing logged yet.</p>{% endif %}
</section>
{% endfor %}
<a class="button" href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}">Add food</a>
</div>
<aside class="food-sidebar" aria-label="Daily nutrition summary">
<section class="food-card" id="food-summary"><h2>Calories</h2>{% if calorie_goal is not None %}<p class="food-remaining">{% if calorie_remaining < 0 %}{{ calorie_remaining|floatformat:0|cut:'-' }} kcal over goal{% else %}{{ calorie_remaining|floatformat:0 }} kcal remaining{% endif %}</p><div class="food-progress" role="progressbar" aria-label="Calories eaten" aria-valuenow="{{ totals.calories_kcal|floatformat:0 }}" aria-valuemin="0" aria-valuemax="{{ calorie_goal }}"><span style="width:{{ calorie_percent }}%"></span></div><p>{{ totals.calories_kcal|floatformat:0 }} kcal eaten · Goal: {{ calorie_goal }} kcal</p>{% else %}<p class="food-remaining">{{ totals.calories_kcal|floatformat:0 }} kcal eaten</p><p>No calorie goal. <a href="{% url 'planner:user-settings' %}">Set one in Settings</a>.</p>{% endif %}</section>
<section class="food-macros" id="food-macro-summary" aria-label="Macronutrients">{% for macro in macros %}<article class="food-card food-macro food-macro--{{ macro.color }}"><div class="food-ring" {% if macro.percent is not None %}style="--progress:{{ macro.percent }}%"{% endif %}><span>{% if macro.percent is not None %}{{ macro.percent }}%{% else %}—{% endif %}</span></div><div><h3>{{ macro.label }}</h3><p>{{ macro.eaten|floatformat:1 }} g eaten</p>{% if macro.goal is not None %}<p>{% if macro.remaining < 0 %}{{ macro.remaining|floatformat:1|cut:'-' }} g over target{% else %}{{ macro.remaining|floatformat:1 }} g remaining{% endif %}</p>{% else %}<p>No target</p>{% endif %}</div></article>{% endfor %}</section>
</aside>
</div>
</div>
</div>
+65
View File
@@ -6,6 +6,9 @@ from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction from django.db import IntegrityError, transaction
from django.test import TestCase from django.test import TestCase
from django.urls import reverse from django.urls import reverse
from planner.models import UserSettings
from .services.diary import diary_context
from .models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit from .models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit
@@ -64,3 +67,65 @@ class FoodFoundationTests(TestCase):
form = FoodGoalForm(data={'daily_calorie_goal': '-1', 'carbohydrate_goal_g': '-1', form = FoodGoalForm(data={'daily_calorie_goal': '-1', 'carbohydrate_goal_g': '-1',
'protein_goal_g': '10', 'fat_goal_g': '0'}) 'protein_goal_g': '10', 'fat_goal_g': '0'})
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
def test_diary_totals_and_over_goal(self):
goals = UserSettings.objects.create(user=self.user, daily_calorie_goal=100, protein_goal_g=Decimal('10'))
FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.BREAKFAST,
product=self.product, product_name_snapshot='Yoghurt', amount=Decimal('100'), unit=Unit.GRAM,
calories_kcal=Decimal('80'), protein_g=Decimal('4'))
FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.DINNER,
product_name_snapshot='Soup', amount=Decimal('100'), unit=Unit.GRAM,
calories_kcal=Decimal('55'), protein_g=Decimal('3'))
context = diary_context(self.user, date(2026, 10, 3))
self.assertEqual(context['totals']['calories_kcal'], Decimal('135'))
self.assertEqual(context['totals']['protein_g'], Decimal('7'))
self.assertEqual(context['calorie_remaining'], Decimal('-35'))
self.assertEqual(context['meals'][0]['calories'], Decimal('80'))
self.assertEqual(context['meals'][2]['calories'], Decimal('55'))
self.assertEqual(context['macros'][0]['percent'], None)
self.client.force_login(self.user)
response = self.client.get(reverse('food:diary'), {'date': '2026-10-03'})
self.assertContains(response, '35 kcal over goal')
self.assertContains(response, 'No target')
self.assertContains(response, 'date=2026-10-02')
self.assertContains(response, 'date=2026-10-04')
def test_bad_date_and_user_isolation(self):
FoodLogEntry.objects.create(user=self.other, date=date(2026, 10, 3), meal=MealType.LUNCH,
product_name_snapshot='Private food', amount=Decimal('100'), unit=Unit.GRAM,
calories_kcal=Decimal('999'))
self.client.force_login(self.user)
self.assertEqual(self.client.get(reverse('food:diary'), {'date': 'not-a-date'}).status_code, 400)
response = self.client.get(reverse('food:diary'), {'date': '2026-10-03'})
self.assertNotContains(response, 'Private food')
self.assertEqual(diary_context(self.user, date(2026, 10, 3))['totals']['calories_kcal'], 0)
def test_add_edit_delete_and_htmx_fragment(self):
self.product.energy_kcal_100 = Decimal('60')
self.product.protein_100 = Decimal('4')
self.product.save()
self.client.force_login(self.user)
add_url = reverse('food:add')
response = self.client.post(add_url, {'date': '2026-10-03', 'product': self.product.pk,
'meal': MealType.BREAKFAST, 'amount': '200', 'unit': 'g'}, HTTP_HX_REQUEST='true')
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'id="food-workspace"')
self.assertContains(response, '120 kcal eaten')
entry = FoodLogEntry.objects.get(user=self.user)
self.assertEqual(entry.protein_g, Decimal('8'))
response = self.client.post(reverse('food:edit', args=[entry.pk]), {'meal': MealType.DINNER,
'amount': '100', 'unit': 'g'}, HTTP_HX_REQUEST='true')
self.assertContains(response, '60 kcal eaten')
entry.refresh_from_db()
self.assertEqual(entry.meal, MealType.DINNER)
self.assertEqual(entry.protein_g, Decimal('4'))
response = self.client.post(reverse('food:delete', args=[entry.pk]), HTTP_HX_REQUEST='true')
self.assertContains(response, '0 kcal eaten')
self.assertFalse(FoodLogEntry.objects.filter(pk=entry.pk).exists())
def test_cannot_edit_or_delete_another_users_entry(self):
entry = FoodLogEntry.objects.create(user=self.other, date=date(2026, 10, 3), meal=MealType.LUNCH,
product_name_snapshot='Private food', amount=Decimal('100'), unit=Unit.GRAM)
self.client.force_login(self.user)
self.assertEqual(self.client.get(reverse('food:edit', args=[entry.pk])).status_code, 404)
self.assertEqual(self.client.post(reverse('food:delete', args=[entry.pk])).status_code, 404)
+4
View File
@@ -6,4 +6,8 @@ app_name = 'food'
urlpatterns = [ urlpatterns = [
path('', views.diary, name='diary'), path('', views.diary, name='diary'),
path('add/', views.add_food, name='add'),
path('manual/', views.manual_food, name='manual'),
path('log/<int:pk>/', views.edit_entry, name='edit'),
path('log/<int:pk>/delete/', views.delete_entry, name='delete'),
] ]
+122 -2
View File
@@ -1,7 +1,127 @@
from decimal import Decimal
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from django.shortcuts import render from django.http import HttpResponseBadRequest
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 .services.diary import diary_context, selected_date
def _day(request):
try:
return selected_date(request), None
except ValueError as error:
return None, HttpResponseBadRequest(str(error))
def _save_entry(form, user, day, product):
entry = form.save(commit=False)
entry.user = user
entry.date = day
entry.product = product
entry.product_name_snapshot = product.product_name
entry.brand_snapshot = product.brand
entry.barcode_snapshot = product.barcode
entry.source = product.source
factor = entry.amount / Decimal('100')
for source, target in (
('energy_kcal_100', 'calories_kcal'), ('carbohydrates_100', 'carbohydrates_g'),
('protein_100', 'protein_g'), ('fat_100', 'fat_g'), ('fibre_100', 'fibre_g'),
('sugars_100', 'sugars_g'), ('salt_100', 'salt_g'),
):
value = getattr(product, source)
setattr(entry, target, (value * factor).quantize(Decimal('0.001')) if value is not None else None)
entry.full_clean()
entry.save()
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))
return redirect(f"{reverse('food:diary')}?date={day.isoformat()}")
@login_required @login_required
def diary(request): def diary(request):
return render(request, 'food/diary.html') day, error = _day(request)
if error:
return error
return render(request, 'food/diary.html', diary_context(request.user, day))
@login_required
@require_http_methods(['GET', 'POST'])
def add_food(request):
day, error = _day(request)
if error:
return error
meal = request.GET.get('meal') or request.POST.get('meal') or MealType.BREAKFAST
if meal not in MealType.values:
return HttpResponseBadRequest('Invalid meal.')
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]
products = FoodProduct.objects.filter(owner=request.user).order_by('product_name')
if query:
products = products.filter(product_name__icontains=query)
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)
return _diary_response(request, day)
return render(request, 'food/add.html', {'day': day, 'meal': meal, 'products': products[:40],
'product': product, 'form': form, 'query': query})
@login_required
@require_http_methods(['GET', 'POST'])
def manual_food(request):
day, error = _day(request)
if error:
return error
meal = request.GET.get('meal') or request.POST.get('meal') or MealType.BREAKFAST
if meal not in MealType.values:
return HttpResponseBadRequest('Invalid meal.')
form = ManualFoodForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
product = form.save(commit=False)
product.owner = request.user
product.save()
return redirect(f"{reverse('food:add')}?date={day}&meal={meal}&product={product.pk}")
return render(request, 'food/manual.html', {'form': form, 'day': day, 'meal': meal})
@login_required
@require_http_methods(['GET', 'POST'])
def edit_entry(request, pk):
entry = get_object_or_404(FoodLogEntry, pk=pk, user=request.user)
product = entry.product
original_amount = entry.amount
original_nutrients = {field: getattr(entry, field) for field in
('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')}
form = FoodLogForm(request.POST or None, instance=entry, product=product)
if request.method == 'POST' and form.is_valid():
updated = form.save(commit=False)
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()
return _diary_response(request, entry.date)
return render(request, 'food/edit.html', {'entry': entry, 'form': form})
@login_required
@require_POST
def delete_entry(request, pk):
entry = get_object_or_404(FoodLogEntry, pk=pk, user=request.user)
day = entry.date
entry.delete()
return _diary_response(request, day)