quantity fields in food log and recipe upload drop zone

This commit is contained in:
Joren de Graaf
2026-10-15 20:35:56 +02:00
parent f36f05b9bc
commit 86e3afaca7
25 changed files with 420 additions and 67 deletions
+16
View File
@@ -149,6 +149,22 @@ class FoodLogForm(forms.ModelForm):
return data return data
class FoodLogEditForm(FoodLogForm):
class Meta(FoodLogForm.Meta):
fields = FoodLogForm.Meta.fields + ('quantity',)
labels = {**FoodLogForm.Meta.labels, 'quantity': 'Quantity (portions)'}
widgets = {**FoodLogForm.Meta.widgets,
'quantity': forms.NumberInput(attrs={'min': '0.01', 'step': '0.01'})}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Older clients may omit the new field; keep the saved quantity in that case.
self.fields['quantity'].required = False
def clean_quantity(self):
return self.cleaned_data['quantity'] if self.cleaned_data['quantity'] is not None else self.instance.quantity
class FoodProductHydrationForm(forms.ModelForm): class FoodProductHydrationForm(forms.ModelForm):
class Meta: class Meta:
model = FoodProduct model = FoodProduct
+21
View File
@@ -0,0 +1,21 @@
from decimal import Decimal
from django.core.validators import MinValueValidator
from django.db import migrations, models
from django.db.models import Q
class Migration(migrations.Migration):
dependencies = [('food', '0010_alter_foodlogentry_unit')]
operations = [
migrations.AddField(
model_name='foodlogentry', name='quantity',
field=models.DecimalField(decimal_places=2, default=1, max_digits=7,
validators=[MinValueValidator(Decimal('0.01'))]),
),
migrations.AddConstraint(
model_name='foodlogentry',
constraint=models.CheckConstraint(condition=Q(quantity__gt=0), name='food_positive_log_quantity'),
),
]
+8
View File
@@ -1,4 +1,5 @@
import uuid import uuid
from decimal import Decimal
from django.conf import settings from django.conf import settings
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
@@ -79,6 +80,8 @@ class FoodLogEntry(models.Model):
barcode_snapshot = models.CharField(max_length=64, blank=True) barcode_snapshot = models.CharField(max_length=64, blank=True)
portion_label_snapshot = models.CharField(max_length=100, blank=True) portion_label_snapshot = models.CharField(max_length=100, blank=True)
amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE) amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE)
quantity = models.DecimalField(max_digits=7, decimal_places=2, default=1,
validators=[MinValueValidator(Decimal('0.01'))])
unit = models.CharField(max_length=8, choices=[*Unit.choices, ('servings', 'servings')]) unit = models.CharField(max_length=8, choices=[*Unit.choices, ('servings', 'servings')])
beverage_volume_ml = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) beverage_volume_ml = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
hydration_amount_ml = models.DecimalField(max_digits=10, decimal_places=3, default=0, validators=NON_NEGATIVE) hydration_amount_ml = models.DecimalField(max_digits=10, decimal_places=3, default=0, validators=NON_NEGATIVE)
@@ -99,6 +102,11 @@ class FoodLogEntry(models.Model):
class Meta: class Meta:
ordering = ('date', 'time', 'pk') ordering = ('date', 'time', 'pk')
constraints = [models.CheckConstraint(condition=Q(quantity__gt=0), name='food_positive_log_quantity')]
def effective_nutrient(self, name):
value = getattr(self, name)
return value * self.quantity if value is not None else None
def clean(self): def clean(self):
super().clean() super().clean()
+10 -8
View File
@@ -28,22 +28,24 @@ def diary_context(user, day, language='en'):
entries = list(FoodLogEntry.objects.filter(user=user, date=day).select_related('product', 'recipe_cooking_run') entries = list(FoodLogEntry.objects.filter(user=user, date=day).select_related('product', 'recipe_cooking_run')
.prefetch_related('attachments').defer('product__raw_data')) .prefetch_related('attachments').defer('product__raw_data'))
for entry in entries: for entry in entries:
entry.effective_calories = entry.effective_nutrient('calories_kcal')
run = getattr(entry, 'recipe_cooking_run', None) run = getattr(entry, 'recipe_cooking_run', None)
entry.nutrition_incomplete = bool(run and any( entry.nutrition_incomplete = bool(run and any(
not row.get('complete', False) for row in run.nutrition_snapshot.values())) not row.get('complete', False) for row in run.nutrition_snapshot.values()))
totals = {name: sum((getattr(entry, name) or ZERO for entry in entries), ZERO) for name in names = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')
('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g')} totals = {name: sum((entry.effective_nutrient(name) or ZERO for entry in entries), ZERO)
fibre_values = [entry.fibre_g for entry in entries if entry.fibre_g is not None] if all(getattr(entry, name) is not None for entry in entries) else None for name in names}
fibre_incomplete = len(fibre_values) != len(entries) or any( fibre_incomplete = totals['fibre_g'] is None or any(
(getattr(entry, 'recipe_cooking_run', None) and (getattr(entry, 'recipe_cooking_run', None) and
not entry.recipe_cooking_run.nutrition_snapshot.get('fibre_g', {}).get('complete', False)) not entry.recipe_cooking_run.nutrition_snapshot.get('fibre_g', {}).get('complete', False))
for entry in entries) for entry in entries)
totals['fibre_g'] = sum(fibre_values, ZERO) if fibre_values or not entries else None if fibre_incomplete:
totals['fibre_g'] = sum((entry.effective_nutrient('fibre_g') or ZERO for entry in entries), ZERO) if any(entry.fibre_g is not None for entry in entries) else None
meals = [] meals = []
for key, label in MealType.choices: for key, label in MealType.choices:
items = [entry for entry in entries if entry.meal == key] items = [entry for entry in entries if entry.meal == key]
meals.append({'key': key, 'label': label, 'entries': items, meals.append({'key': key, 'label': label, 'entries': items,
'calories': sum((entry.calories_kcal or ZERO for entry in items), ZERO)}) 'calories': sum((entry.effective_calories or ZERO for entry in items), ZERO)})
macros = [] macros = []
for label, name, goal, color in ( for label, name, goal, color in (
('Protein', 'protein_g', goals.protein_goal_g, 'blue'), ('Protein', 'protein_g', goals.protein_goal_g, 'blue'),
@@ -63,5 +65,5 @@ def diary_context(user, day, language='en'):
return {'day': day, 'previous_day': day - timedelta(days=1), 'next_day': day + timedelta(days=1), return {'day': day, 'previous_day': day - timedelta(days=1), 'next_day': day + timedelta(days=1),
'meals': meals, 'totals': totals, 'macros': macros, 'help_language': language, 'meals': meals, 'totals': totals, 'macros': macros, 'help_language': language,
'calorie_goal': calorie_goal, 'calorie_goal': calorie_goal,
'calorie_remaining': Decimal(calorie_goal) - calories if calorie_goal is not None else None, 'calorie_remaining': Decimal(calorie_goal) - calories if calorie_goal is not None and calories is not None else None,
'calorie_percent': min(100, int(calories * 100 / calorie_goal)) if calorie_goal else 0} 'calorie_percent': min(100, int(calories * 100 / calorie_goal)) if calorie_goal and calories is not None else 0}
+2
View File
@@ -88,3 +88,5 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317}
.inventory-heading-actions{display:flex;align-items:center;justify-content:flex-end;gap:.5rem;flex-wrap:wrap} .inventory-heading-actions{display:flex;align-items:center;justify-content:flex-end;gap:.5rem;flex-wrap:wrap}
.inventory-heading-actions .button{min-height:44px} .inventory-heading-actions .button{min-height:44px}
@media(max-width:600px){.inventory-page>.food-heading{align-items:flex-start;flex-wrap:wrap}.inventory-heading-actions{justify-content:flex-start;width:100%}} @media(max-width:600px){.inventory-page>.food-heading{align-items:flex-start;flex-wrap:wrap}.inventory-heading-actions{justify-content:flex-start;width:100%}}
.food-quantity-form{display:flex;align-items:center;gap:.35rem}.food-quantity{font-weight:700;white-space:nowrap}.food-quantity-form button{min-width:44px;min-height:44px;border:1px solid var(--food-border);border-radius:50%;background:var(--food-surface);color:var(--food-ink);font:inherit;font-size:1.4rem;cursor:pointer}.food-quantity-form button:focus-visible{outline:2px solid var(--food-green);outline-offset:2px}.food-quantity-form.htmx-request button{opacity:.6;cursor:progress}.food-screen-reader{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
.food-quantity-controls{display:flex;align-items:center;gap:.35rem;white-space:nowrap}.food-quantity-controls .food-quantity{min-width:2.5ch;text-align:center}.food-quantity-controls .food-quantity-form{margin:0}
+10
View File
@@ -0,0 +1,10 @@
document.addEventListener('htmx:responseError', (event) => {
if (!event.detail.elt?.closest('.food-quantity-form')) return;
const status = document.getElementById('food-quantity-status');
if (status) status.textContent = 'Quantity could not be updated. Reload the diary and try again.';
});
document.addEventListener('htmx:sendError', (event) => {
if (!event.detail.elt?.closest('.food-quantity-form')) return;
const status = document.getElementById('food-quantity-status');
if (status) status.textContent = 'Connection failed. Reload the diary and try again.';
});
+3 -2
View File
@@ -2,7 +2,8 @@
{% load static %} {% load static %}
{% block title %}Food · Tasknest{% endblock %} {% block title %}Food · Tasknest{% endblock %}
{% block content %} {% block content %}
<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261011-help"> <link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261015-quantity">
{% include 'food/partials/diary_content.html' %} {% include 'food/partials/diary_content.html' %}
<script defer src="{% static 'food/nutrient_help.js' %}?v=20261011-help"></script> <script defer src="{% static 'food/quantity.js' %}?v=20261015"></script>
<script defer src="{% static 'food/nutrient_help.js' %}?v=20261015-quantity"></script>
{% endblock %} {% endblock %}
@@ -1,39 +1,19 @@
<div id="food-workspace" class="food-page"><div id="food-diary"> <div id="food-workspace" class="food-page"><div id="food-quantity-status" class="food-screen-reader" role="status" aria-live="polite"></div><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> <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-layout">
<div class="food-meals"> <div class="food-meals">
{% for meal in meals %} {% for meal in meals %}
<section class="food-meal" id="meal-{{ meal.key }}" aria-labelledby="meal-title-{{ meal.key }}"> <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> {% include 'food/partials/meal_heading.html' %}
{% if meal.entries %}<ul class="food-entry-list">{% for entry in meal.entries %} {% if meal.entries %}<ul class="food-entry-list">{% for entry in meal.entries %}
<li class="food-entry"> {% include 'food/partials/entry.html' %}
<div class="food-entry-main">
{% with images=entry.attachments.all %}
{% if images %}<div class="food-entry-images">{% for attachment in images %}<a href="{% url 'food:attachment-file' attachment.api_id %}" target="_blank" rel="noopener" aria-label="View attached image{% if attachment.caption %}: {{ attachment.caption }}{% else %} for {{ entry.product_name_snapshot }}{% endif %}"><img src="{% url 'food:attachment-file' attachment.api_id %}" alt="" loading="lazy"></a>{% endfor %}</div>
{% elif entry.product and entry.product.image_url %}<img src="{{ entry.product.image_url }}" alt="" loading="lazy">{% endif %}
{% endwith %}
<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 }}){% if entry.nutrition_incomplete %} · Incomplete nutrition estimate{% endif %}</small></div>
</div>
<div class="food-entry-actions"><a href="{% url 'food:edit' entry.pk %}" aria-label="Edit {{ entry.product_name_snapshot }}">Edit</a>{% if entry.product %}<a href="{% url 'food:product-hydration' entry.product.pk %}" aria-label="Drink settings for {{ entry.product_name_snapshot }}">Drink settings</a>{% endif %}</div>
</li>
{% endfor %}</ul>{% else %}<p class="food-empty">Nothing logged yet.</p>{% endif %} {% endfor %}</ul>{% else %}<p class="food-empty">Nothing logged yet.</p>{% endif %}
</section> </section>
{% endfor %} {% endfor %}
<a class="button" href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}">Add food</a> <a class="button" href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}">Add food</a>
</div> </div>
<aside class="food-sidebar" aria-label="Daily nutrition summary"> <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> {% include 'food/partials/nutrition_summary.html' %}
<section class="food-macros" id="food-macro-summary" aria-label="Daily nutrition goals">{% for macro in macros %}<article class="food-card food-macro food-macro--{{ macro.color }}" aria-labelledby="food-goal-{{ macro.slug }}">
<button class="food-help-trigger" type="button" aria-label="{% if help_language|slice:':2' == 'nl' %}Hulp bij {{ macro.guidance.title }}{% else %}About {{ macro.guidance.title }}{% endif %}" aria-expanded="false" aria-controls="food-help-{{ macro.slug }}" data-food-help-trigger><span aria-hidden="true">?</span></button>
<div class="food-ring" {% if macro.percent is not None %}style="--progress:{{ macro.percent }}%" role="progressbar" aria-label="{{ macro.label }} progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ macro.percent }}" aria-valuetext="{% if macro.incomplete %}At least {% endif %}{{ macro.eaten|floatformat:1 }} g of {{ macro.goal|floatformat:1 }} g{% if macro.incomplete %}; some food entries have unknown fibre{% endif %}"{% else %}aria-label="{{ macro.label }} progress unknown"{% endif %}><span aria-hidden="true">{% if macro.percent is not None %}{{ macro.percent }}%{% else %}—{% endif %}</span></div>
<div><h3 id="food-goal-{{ macro.slug }}">{{ macro.label }}</h3><p>{% if macro.eaten is None %}Unknown{% elif macro.incomplete %}At least {{ macro.eaten|floatformat:1 }} g{% else %}{{ macro.eaten|floatformat:1 }} g eaten{% endif %}{% if macro.goal is not None %} · {{ macro.goal|floatformat:1 }} g goal{% endif %}</p>{% if macro.incomplete %}<p>Some entries unknown</p>{% elif 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>
<div class="food-help-popover" id="food-help-{{ macro.slug }}" role="region" aria-labelledby="food-help-title-{{ macro.slug }}" hidden>
<div class="food-help-heading"><h4 id="food-help-title-{{ macro.slug }}">{{ macro.guidance.title }}</h4><button type="button" class="food-help-close" data-food-help-close aria-label="{% if help_language|slice:':2' == 'nl' %}Sluiten{% else %}Close{% endif %}">×</button></div>
<p>{{ macro.guidance.explanation }}</p><strong>{% if help_language|slice:':2' == 'nl' %}Goede bronnen:{% else %}Good sources:{% endif %}</strong>
<ul>{% for group, foods in macro.guidance.sources %}<li><strong>{{ group }}</strong>{% if foods %}: {{ foods }}{% endif %}</li>{% endfor %}</ul>
{% if macro.guidance.tip %}<p class="food-help-tip">{{ macro.guidance.tip }}</p>{% endif %}
</div>
</article>{% endfor %}</section>
<section class="food-card food-export" aria-labelledby="food-export-title"><h2 id="food-export-title">Export food diary</h2><p>Download your logged entries as CSV.</p><div class="food-export-actions"><a href="{% url 'food:export' 'week' %}">Current week CSV</a><a href="{% url 'food:export' 'month' %}">Current month CSV</a></div></section> <section class="food-card food-export" aria-labelledby="food-export-title"><h2 id="food-export-title">Export food diary</h2><p>Download your logged entries as CSV.</p><div class="food-export-actions"><a href="{% url 'food:export' 'week' %}">Current week CSV</a><a href="{% url 'food:export' 'month' %}">Current month CSV</a></div></section>
</aside> </aside>
</div> </div>
@@ -1,13 +1,14 @@
{% load static %} {% load static food_quantity %}
<div id="food-workspace" class="food-form-page"> <div id="food-workspace" class="food-form-page">
<a href="{% url 'food:diary' %}?date={{ entry.date|date:'Y-m-d' }}">← Back to diary</a> <a href="{% url 'food:diary' %}?date={{ entry.date|date:'Y-m-d' }}">← Back to diary</a>
<h1>{{ entry.product_name_snapshot }}</h1> <h1>{{ entry.product_name_snapshot }}</h1>
{% if entry.brand_snapshot %}<p>{{ entry.brand_snapshot }}</p>{% endif %} {% if entry.brand_snapshot %}<p>{{ entry.brand_snapshot }}</p>{% endif %}
<div class="food-card food-edit-nutrition"><p>{% 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</p> <div class="food-card food-edit-nutrition"><p>Nutrition at current quantity ({{ entry.quantity|quantity_display }}×):</p><p>{% if entry.effective_calories_kcal is not None %}{{ entry.effective_calories_kcal|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {% if entry.effective_carbohydrates_g is not None %}{{ entry.effective_carbohydrates_g|floatformat:-1 }}{% else %}—{% endif %} g carbs · {% if entry.effective_protein_g is not None %}{{ entry.effective_protein_g|floatformat:-1 }}{% else %}—{% endif %} g protein · {% if entry.effective_fat_g is not None %}{{ entry.effective_fat_g|floatformat:-1 }}{% else %}—{% endif %} 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> <details><summary>Nutrition information</summary><dl><dt>Fibre</dt><dd>{{ entry.effective_fibre_g|default_if_none:'—' }} g</dd><dt>Sugars</dt><dd>{{ entry.effective_sugars_g|default_if_none:'—' }} g</dd><dt>Salt</dt><dd>{{ entry.effective_salt_g|default_if_none:'—' }} g</dd></dl></details>
</div> </div>
<form method="post" class="food-card food-entry-form" hx-post="{% url 'food:edit' entry.pk %}" hx-target="#food-workspace" hx-swap="outerHTML">{% csrf_token %} <form method="post" class="food-card food-entry-form" hx-post="{% url 'food:edit' entry.pk %}" hx-target="#food-workspace" hx-swap="outerHTML">{% csrf_token %}
{% include 'food/partials/portion_fields.html' %} {% include 'food/partials/portion_fields.html' %}
<div class="form-field">{{ form.quantity.label_tag }}{{ form.quantity }}{{ form.quantity.errors }}<small>Multiplies the selected portion. For example, 2 means two of that portion.</small></div>
<button class="button" type="submit">Save changes</button> <button class="button" type="submit">Save changes</button>
</form> </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">{% csrf_token %}<button type="submit" class="button button--secondary">Delete entry</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">{% csrf_token %}<button type="submit" class="button button--secondary">Delete entry</button></form>
@@ -0,0 +1,11 @@
{% load food_quantity %}
<li class="food-entry" id="food-entry-{{ entry.pk }}">
<div class="food-entry-main">
{% with images=entry.attachments.all %}
{% if images %}<div class="food-entry-images">{% for attachment in images %}<a href="{% url 'food:attachment-file' attachment.api_id %}" target="_blank" rel="noopener" aria-label="View attached image{% if attachment.caption %}: {{ attachment.caption }}{% else %} for {{ entry.product_name_snapshot }}{% endif %}"><img src="{% url 'food:attachment-file' attachment.api_id %}" alt="" loading="lazy"></a>{% endfor %}</div>
{% elif entry.product and entry.product.image_url %}<img src="{{ entry.product.image_url }}" alt="" loading="lazy">{% endif %}
{% endwith %}
<div><strong>{{ entry.product_name_snapshot }}</strong>{% if entry.brand_snapshot %}<span>{{ entry.brand_snapshot }}</span>{% endif %}<small>{% if entry.effective_calories is not None %}{{ entry.effective_calories|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {% if entry.portion_label_snapshot %}{{ entry.portion_label_snapshot }} {% endif %}({{ entry.amount|floatformat:-3 }} {{ entry.unit }}){% if entry.nutrition_incomplete %} · Incomplete nutrition estimate{% endif %}</small></div>
</div>
<div class="food-entry-actions"><div class="food-quantity-controls">{% if entry.quantity > 1 %}<form hx-post="{% url 'food:decrement' entry.pk %}" hx-target="#food-entry-{{ entry.pk }}" hx-swap="outerHTML" hx-sync="closest .food-entry-list:queue all" method="post" class="food-quantity-form">{% csrf_token %}<button type="submit" aria-label="Remove one portion of {{ entry.product_name_snapshot }}" title="Remove one portion">−</button></form>{% endif %}<span class="food-quantity" aria-label="Quantity {{ entry.quantity|quantity_display }} portions">{{ entry.quantity|quantity_display }}×</span><form hx-post="{% url 'food:increment' entry.pk %}" hx-target="#food-entry-{{ entry.pk }}" hx-swap="outerHTML" hx-sync="closest .food-entry-list:queue all" method="post" class="food-quantity-form">{% csrf_token %}<button type="submit" aria-label="Add one portion of {{ entry.product_name_snapshot }}" title="Add one portion">+</button></form></div><a href="{% url 'food:edit' entry.pk %}" aria-label="Edit {{ entry.product_name_snapshot }}">Edit</a>{% if entry.product %}<a href="{% url 'food:product-hydration' entry.product.pk %}" aria-label="Drink settings for {{ entry.product_name_snapshot }}">Drink settings</a>{% endif %}</div>
</li>
@@ -0,0 +1 @@
<div class="food-meal-heading" id="food-meal-heading-{{ meal.key }}"><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>
@@ -0,0 +1,14 @@
<div id="food-nutrition-summary">
<section class="food-card" id="food-summary"><h2>Calories</h2>{% if calorie_goal is not None and totals.calories_kcal 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">{% if totals.calories_kcal is None %}Calories unknown{% else %}{{ totals.calories_kcal|floatformat:0 }} kcal eaten{% endif %}</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="Daily nutrition goals">{% for macro in macros %}<article class="food-card food-macro food-macro--{{ macro.color }}" aria-labelledby="food-goal-{{ macro.slug }}">
<button class="food-help-trigger" type="button" aria-label="{% if help_language|slice:':2' == 'nl' %}Hulp bij {{ macro.guidance.title }}{% else %}About {{ macro.guidance.title }}{% endif %}" aria-expanded="false" aria-controls="food-help-{{ macro.slug }}" data-food-help-trigger><span aria-hidden="true">?</span></button>
<div class="food-ring" {% if macro.percent is not None %}style="--progress:{{ macro.percent }}%" role="progressbar" aria-label="{{ macro.label }} progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ macro.percent }}" aria-valuetext="{% if macro.incomplete %}At least {% endif %}{{ macro.eaten|floatformat:1 }} g of {{ macro.goal|floatformat:1 }} g{% if macro.incomplete %}; some food entries have unknown fibre{% endif %}"{% else %}aria-label="{{ macro.label }} progress unknown"{% endif %}><span aria-hidden="true">{% if macro.percent is not None %}{{ macro.percent }}%{% else %}—{% endif %}</span></div>
<div><h3 id="food-goal-{{ macro.slug }}">{{ macro.label }}</h3><p>{% if macro.eaten is None %}Unknown{% elif macro.incomplete %}At least {{ macro.eaten|floatformat:1 }} g{% else %}{{ macro.eaten|floatformat:1 }} g eaten{% endif %}{% if macro.goal is not None %} · {{ macro.goal|floatformat:1 }} g goal{% endif %}</p>{% if macro.incomplete %}<p>Some entries unknown</p>{% elif 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>
<div class="food-help-popover" id="food-help-{{ macro.slug }}" role="region" aria-labelledby="food-help-title-{{ macro.slug }}" hidden>
<div class="food-help-heading"><h4 id="food-help-title-{{ macro.slug }}">{{ macro.guidance.title }}</h4><button type="button" class="food-help-close" data-food-help-close aria-label="{% if help_language|slice:':2' == 'nl' %}Sluiten{% else %}Close{% endif %}">×</button></div>
<p>{{ macro.guidance.explanation }}</p><strong>{% if help_language|slice:':2' == 'nl' %}Goede bronnen:{% else %}Good sources:{% endif %}</strong>
<ul>{% for group, foods in macro.guidance.sources %}<li><strong>{{ group }}</strong>{% if foods %}: {{ foods }}{% endif %}</li>{% endfor %}</ul>
{% if macro.guidance.tip %}<p class="food-help-tip">{{ macro.guidance.tip }}</p>{% endif %}
</div>
</article>{% endfor %}</section>
</div>
+10
View File
@@ -0,0 +1,10 @@
from decimal import Decimal
from django import template
register = template.Library()
@register.filter
def quantity_display(value):
return format(Decimal(value).normalize(), 'f')
+80
View File
@@ -0,0 +1,80 @@
from datetime import date
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.test import Client
from django.urls import reverse
from .models import FoodLogEntry
from .services.diary import diary_context
class FoodQuantityTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username='quantity-owner', password='password')
self.other = get_user_model().objects.create_user(username='quantity-other', password='password')
self.day = date(2026, 10, 3)
self.entry = FoodLogEntry.objects.create(user=self.user, date=self.day, meal='lunch',
product_name_snapshot='Soup', amount=Decimal('250'), unit='ml',
calories_kcal=Decimal('100'), protein_g=Decimal('4'), carbohydrates_g=Decimal('12'),
fat_g=Decimal('2'), fibre_g=None)
self.client.force_login(self.user)
def test_increment_preserves_snapshot_and_updates_day(self):
url = reverse('food:increment', args=[self.entry.pk])
for _ in range(2):
response = self.client.post(url, HTTP_HX_REQUEST='true')
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'hx-swap-oob="outerHTML"')
self.entry.refresh_from_db()
self.assertEqual(self.entry.quantity, Decimal('3.00'))
self.assertEqual(self.entry.calories_kcal, Decimal('100'))
self.assertEqual(diary_context(self.user, self.day)['totals']['calories_kcal'], Decimal('300'))
self.assertEqual(diary_context(self.user, date(2026, 10, 4))['totals']['calories_kcal'], 0)
self.assertEqual(diary_context(self.user, self.day)['totals']['fibre_g'], None)
def test_other_user_cannot_increment(self):
self.client.force_login(self.other)
self.assertEqual(self.client.post(reverse('food:increment', args=[self.entry.pk])).status_code, 404)
self.entry.refresh_from_db()
self.assertEqual(self.entry.quantity, Decimal('1.00'))
def test_fractional_quantity_and_csrf(self):
self.entry.quantity = Decimal('1.25')
self.entry.save(update_fields=['quantity'])
self.assertEqual(diary_context(self.user, self.day)['totals']['calories_kcal'], Decimal('125.00000'))
url = reverse('food:increment', args=[self.entry.pk])
csrf_client = Client(enforce_csrf_checks=True)
csrf_client.force_login(self.user)
self.assertEqual(csrf_client.post(url).status_code, 403)
self.entry.refresh_from_db()
self.assertEqual(self.entry.quantity, Decimal('1.25'))
def test_edit_quantity_and_decrement_floor(self):
edit_url = reverse('food:edit', args=[self.entry.pk])
self.assertContains(self.client.get(edit_url), 'Quantity (portions)')
response = self.client.post(edit_url, {'meal': 'lunch', 'amount': '250', 'unit': 'ml',
'quantity': '2.50'})
self.assertEqual(response.status_code, 302)
self.entry.refresh_from_db()
self.assertEqual(self.entry.quantity, Decimal('2.50'))
self.assertEqual(self.entry.calories_kcal, Decimal('100'))
url = reverse('food:decrement', args=[self.entry.pk])
response = self.client.post(url, HTTP_HX_REQUEST='true')
self.assertContains(response, '1.5×')
self.assertContains(response, 'Remove one portion of Soup')
self.entry.refresh_from_db()
self.assertEqual(self.entry.quantity, Decimal('1.50'))
response = self.client.post(url, HTTP_HX_REQUEST='true')
self.assertContains(response, '0.5×')
self.assertNotContains(response, 'Remove one portion of Soup')
self.assertEqual(self.client.post(url).status_code, 409)
self.entry.refresh_from_db()
self.assertEqual(self.entry.quantity, Decimal('0.50'))
def test_other_user_cannot_decrement(self):
self.entry.quantity = Decimal('2')
self.entry.save(update_fields=['quantity'])
self.client.force_login(self.other)
self.assertEqual(self.client.post(reverse('food:decrement', args=[self.entry.pk])).status_code, 404)
+2
View File
@@ -26,6 +26,8 @@ urlpatterns = [
path('not-found/', views.product_not_found, name='not-found'), path('not-found/', views.product_not_found, name='not-found'),
path('manual/', views.manual_food, name='manual'), path('manual/', views.manual_food, name='manual'),
path('log/<int:pk>/', views.edit_entry, name='edit'), path('log/<int:pk>/', views.edit_entry, name='edit'),
path('log/<int:pk>/increment/', views.increment_entry, name='increment'),
path('log/<int:pk>/decrement/', views.decrement_entry, name='decrement'),
path('log/<int:pk>/delete/', views.delete_entry, name='delete'), path('log/<int:pk>/delete/', views.delete_entry, name='delete'),
path('attachments/<uuid:identifier>/file/', views.attachment_file, name='attachment-file'), path('attachments/<uuid:identifier>/file/', views.attachment_file, name='attachment-file'),
path('product/<int:pk>/favourite/', views.toggle_favourite, name='toggle-favourite'), path('product/<int:pk>/favourite/', views.toggle_favourite, name='toggle-favourite'),
+48 -3
View File
@@ -9,7 +9,9 @@ from urllib.parse import urlencode
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from django.http import FileResponse, Http404, HttpResponse, HttpResponseBadRequest, StreamingHttpResponse from django.http import FileResponse, Http404, HttpResponse, HttpResponseBadRequest, StreamingHttpResponse
from django.contrib import messages from django.contrib import messages
from django.db.models import Q from django.db.models import Q, F
from django.template.loader import render_to_string
from django.utils.html import format_html
from django.db.models import Max from django.db.models import Max
from django.db import transaction from django.db import transaction
from django.shortcuts import get_object_or_404, redirect, render from django.shortcuts import get_object_or_404, redirect, render
@@ -18,7 +20,7 @@ from django.utils.translation import get_language_from_request
from django.views.decorators.http import require_GET, require_http_methods, require_POST from django.views.decorators.http import require_GET, require_http_methods, require_POST
from django.views.decorators.cache import never_cache from django.views.decorators.cache import never_cache
from .forms import FoodLogForm, ManualFoodForm from .forms import FoodLogEditForm, FoodLogForm, ManualFoodForm
from .models import FoodFavourite, FoodLogAttachment, FoodLogEntry, FoodPortion, FoodProduct, MealType from .models import FoodFavourite, FoodLogAttachment, FoodLogEntry, FoodPortion, FoodProduct, MealType
from .services.diary import diary_context, selected_date from .services.diary import diary_context, selected_date
from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search
@@ -362,7 +364,7 @@ def edit_entry(request, pk):
original_amount = entry.amount original_amount = entry.amount
original_nutrients = {field: getattr(entry, field) for field in original_nutrients = {field: getattr(entry, field) for field in
('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')} ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')}
form = FoodLogForm(request.POST or None, instance=entry, product=product) form = FoodLogEditForm(request.POST or None, instance=entry, product=product)
if request.method == 'POST' and form.is_valid(): if request.method == 'POST' and form.is_valid():
updated = form.save(commit=False) updated = form.save(commit=False)
factor = updated.amount / original_amount factor = updated.amount / original_amount
@@ -380,6 +382,8 @@ def edit_entry(request, pk):
if product: if product:
_save_custom_portion(form, request.user, product, updated) _save_custom_portion(form, request.user, product, updated)
return _diary_response(request, entry.date) return _diary_response(request, entry.date)
for name in ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g'):
setattr(entry, f'effective_{name}', entry.effective_nutrient(name))
template = 'food/partials/edit_content.html' if request.method == 'POST' and request.headers.get('HX-Request') == 'true' else 'food/edit.html' 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, return render(request, template, {'entry': entry, 'form': form, 'product': product,
'portion_options': _portion_options(form, product)}) 'portion_options': _portion_options(form, product)})
@@ -394,6 +398,47 @@ def delete_entry(request, pk):
return _diary_response(request, day) return _diary_response(request, day)
@login_required
@require_POST
def increment_entry(request, pk):
return _change_entry_quantity(request, pk, Decimal('1.00'))
@login_required
@require_POST
def decrement_entry(request, pk):
return _change_entry_quantity(request, pk, Decimal('-1.00'))
def _change_entry_quantity(request, pk, delta):
entry = get_object_or_404(FoodLogEntry, pk=pk, user=request.user)
with transaction.atomic():
entries = FoodLogEntry.objects.filter(pk=entry.pk, user=request.user)
if delta < 0:
entries = entries.filter(quantity__gt=1)
changed = entries.update(quantity=F('quantity') + delta)
entry.refresh_from_db()
if not changed:
return HttpResponse('Quantity cannot be reduced further. Reload the diary.', status=409)
if request.headers.get('HX-Request') != 'true':
return _diary_response(request, entry.date)
context = diary_context(request.user, entry.date, get_language_from_request(request))
for meal in context['meals']:
for item in meal['entries']:
if item.pk == entry.pk:
entry = item
break
html = render_to_string('food/partials/entry.html', {'entry': entry}, request=request)
summary = render_to_string('food/partials/nutrition_summary.html', context, request=request)
meal = next(meal for meal in context['meals'] if meal['key'] == entry.meal)
heading = render_to_string('food/partials/meal_heading.html', {'meal': meal, 'day': entry.date}, request=request)
response = HttpResponse(html + summary.replace('id="food-nutrition-summary"', 'id="food-nutrition-summary" hx-swap-oob="outerHTML"', 1)
+ heading.replace('id="food-meal-heading-', 'hx-swap-oob="outerHTML" id="food-meal-heading-', 1)
+ format_html('<div id="food-quantity-status" hx-swap-oob="innerHTML">{} quantity updated to {} portions.</div>', entry.product_name_snapshot, entry.quantity.normalize()))
response['HX-Trigger'] = 'hydrationChanged'
return response
@login_required @login_required
@require_http_methods(['GET', 'POST']) @require_http_methods(['GET', 'POST'])
def product_hydration(request, pk): def product_hydration(request, pk):
+3 -3
View File
@@ -18,7 +18,7 @@ def daily_hydration(user, day):
settings = UserSettings.objects.get_or_create(user=user)[0] settings = UserSettings.objects.get_or_create(user=user)[0]
manual = sum((entry.amount_ml for entry in WaterIntakeEntry.objects.filter( manual = sum((entry.amount_ml for entry in WaterIntakeEntry.objects.filter(
user=user, recorded_at__gte=start, recorded_at__lt=end)), ZERO) user=user, recorded_at__gte=start, recorded_at__lt=end)), ZERO)
food = (sum((entry.hydration_amount_ml for entry in FoodLogEntry.objects.filter(user=user, date=day)), ZERO) food = (sum((entry.hydration_amount_ml * entry.quantity for entry in FoodLogEntry.objects.filter(user=user, date=day)), ZERO)
if settings.auto_count_food_drinks else ZERO) if settings.auto_count_food_drinks else ZERO)
total = manual + food total = manual + food
return {'date': day, 'manual_ml': manual, 'food_ml': food, 'total_ml': total, return {'date': day, 'manual_ml': manual, 'food_ml': food, 'total_ml': total,
@@ -43,9 +43,9 @@ def hydration_context(user, now=None):
if settings.auto_count_food_drinks: if settings.auto_count_food_drinks:
for entry in FoodLogEntry.objects.filter(user=user, date__gte=start, for entry in FoodLogEntry.objects.filter(user=user, date__gte=start,
date__lt=start + timedelta(days=7)): date__lt=start + timedelta(days=7)):
totals[entry.date] += entry.hydration_amount_ml totals[entry.date] += entry.hydration_amount_ml * entry.quantity
if entry.date == today: if entry.date == today:
food_today += entry.hydration_amount_ml food_today += entry.hydration_amount_ml * entry.quantity
total = totals[today] total = totals[today]
last = entries.filter( last = entries.filter(
recorded_at__gte=timezone.make_aware(datetime.combine(today, time.min), zone), recorded_at__gte=timezone.make_aware(datetime.combine(today, time.min), zone),
+12 -8
View File
@@ -27,7 +27,7 @@ class RecipeForm(forms.ModelForm):
'description': forms.Textarea(attrs={'rows': 3}), 'description': forms.Textarea(attrs={'rows': 3}),
'instructions_markdown': forms.Textarea(attrs={'rows': 10}), 'instructions_markdown': forms.Textarea(attrs={'rows': 10}),
'notes_markdown': forms.Textarea(attrs={'rows': 4}), 'notes_markdown': forms.Textarea(attrs={'rows': 4}),
'photo': forms.ClearableFileInput(attrs={'accept': 'image/jpeg,image/png,image/webp'}), 'photo': forms.FileInput(attrs={'accept': 'image/jpeg,image/png,image/webp'}),
'preparation_minutes': forms.NumberInput(attrs={'min': 0}), 'preparation_minutes': forms.NumberInput(attrs={'min': 0}),
'cooking_minutes': forms.NumberInput(attrs={'min': 0}), 'cooking_minutes': forms.NumberInput(attrs={'min': 0}),
'default_servings': forms.NumberInput(attrs={'min': '.01', 'step': '.01'}), 'default_servings': forms.NumberInput(attrs={'min': '.01', 'step': '.01'}),
@@ -48,6 +48,17 @@ class RecipeForm(forms.ModelForm):
def clean_photo(self): def clean_photo(self):
photo = self.cleaned_data.get('photo') photo = self.cleaned_data.get('photo')
return validate_recipe_photo(photo)
def save(self, commit=True):
recipe = super().save(commit=False)
recipe.tags = self.cleaned_data['tags_text']
if commit:
recipe.save()
return recipe
def validate_recipe_photo(photo):
if not isinstance(photo, UploadedFile): if not isinstance(photo, UploadedFile):
return photo return photo
if photo.size > 5 * 1024 * 1024: if photo.size > 5 * 1024 * 1024:
@@ -65,13 +76,6 @@ class RecipeForm(forms.ModelForm):
photo.seek(0) photo.seek(0)
return photo return photo
def save(self, commit=True):
recipe = super().save(commit=False)
recipe.tags = self.cleaned_data['tags_text']
if commit:
recipe.save()
return recipe
class RecipeIngredientForm(forms.ModelForm): class RecipeIngredientForm(forms.ModelForm):
class Meta: class Meta:
@@ -0,0 +1,89 @@
(() => {
const supported = new Set(['image/jpeg', 'image/png', 'image/webp']);
const check = (file, status) => {
if (!file) return false;
if (!supported.has(file.type)) {
status.textContent = 'Choose a JPEG, PNG or WebP image.';
return false;
}
if (file.size > 5 * 1024 * 1024) {
status.textContent = 'Choose an image smaller than 5 MB.';
return false;
}
return true;
};
const drop = (zone, input, onFile) => {
if (!zone || !input) return;
zone.addEventListener('dragover', event => {
if (!Array.from(event.dataTransfer?.types || []).includes('Files')) return;
event.preventDefault();
zone.classList.add('is-dragging');
});
zone.addEventListener('dragleave', () => zone.classList.remove('is-dragging'));
zone.addEventListener('drop', event => {
event.preventDefault();
zone.classList.remove('is-dragging');
if (!event.dataTransfer?.files.length) return;
input.files = event.dataTransfer.files;
onFile();
});
};
const detail = document.querySelector('[data-photo-upload]');
if (detail) {
const input = detail.querySelector('input[type=file]');
const status = detail.querySelector('[data-photo-status]');
const zone = detail.querySelector('.recipes-photo-placeholder');
const submit = detail.querySelector('.recipe-photo-submit');
if (submit) submit.hidden = true;
const upload = () => {
const file = input.files[0];
if (!check(file, status)) return;
status.textContent = `Uploading ${file.name}…`;
detail.requestSubmit();
};
input.addEventListener('change', upload);
drop(zone, input, upload);
}
const editor = document.querySelector('[data-photo-editor]');
if (editor) {
const input = editor.querySelector('input[type=file]');
const zone = editor.querySelector('.recipe-photo-editor__zone');
const preview = editor.querySelector('[data-photo-preview]');
const prompt = editor.querySelector('[data-photo-prompt]');
const remove = editor.querySelector('[data-photo-remove]');
const checkbox = editor.parentElement.querySelector('input[name=remove_photo]');
const status = editor.parentElement.querySelector('[data-photo-edit-status]');
const hasPhoto = !preview.hidden;
let previewUrl;
const selected = () => {
const file = input.files[0];
if (!file) return;
if (!check(file, status)) { input.value = ''; return; }
if (previewUrl) URL.revokeObjectURL(previewUrl);
previewUrl = URL.createObjectURL(file);
preview.src = previewUrl;
preview.hidden = false;
checkbox.checked = false;
remove.hidden = false;
prompt.firstChild.textContent = 'Click or drop to change photo';
status.textContent = `${file.name} selected. Save the recipe to upload it.`;
};
input.addEventListener('change', selected);
drop(zone, input, () => input.dispatchEvent(new Event('change', {bubbles: true})));
remove.addEventListener('click', () => {
input.value = '';
if (previewUrl) URL.revokeObjectURL(previewUrl);
previewUrl = null;
preview.removeAttribute('src');
preview.hidden = true;
checkbox.checked = hasPhoto;
remove.hidden = true;
prompt.firstChild.textContent = 'Click or drop a photo here';
status.textContent = hasPhoto ? 'Current photo will be removed when you save.' : 'Selected photo cleared.';
checkbox.dispatchEvent(new Event('change', {bubbles: true}));
input.focus();
});
}
})();
+6
View File
@@ -40,3 +40,9 @@ body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI,body[da
.recipes-saved-badge{align-self:center;padding:5px 8px;border-radius:99px;background:#e1f2e8;color:#235943;font-size:.72rem;font-weight:700} .recipes-saved-badge{align-self:center;padding:5px 8px;border-radius:99px;background:#e1f2e8;color:#235943;font-size:.72rem;font-weight:700}
.cook-later{max-width:850px;margin:0 auto;padding:20px;color:var(--recipe-ink,#25292e)}.cook-later h1{margin:15px 0 5px;font-family:Fraunces,Georgia,serif}.cook-later__list{display:grid;gap:12px;margin-top:24px}.cook-later__item{display:flex;align-items:center;justify-content:space-between;gap:20px;padding:18px;border:1px solid var(--recipe-line,#d0d8d0);border-radius:14px;background:var(--recipe-surface,#fff)}.cook-later__item h2{margin:0;font-size:1.15rem}.cook-later__item p{margin:6px 0}.cook-later__item small{color:var(--recipe-muted,#687178)}.cook-later__item button{min-height:44px;padding:8px 14px;border:1px solid #b94a55;border-radius:9px;background:transparent;color:#a12435;cursor:pointer}body[data-theme=dark] .cook-later__item button{color:#ffb3bb}body[data-theme=dark] .recipes-saved-badge{background:#294d38;color:#b7e8c5}@media(max-width:600px){.cook-later__item{align-items:flex-start;flex-direction:column}} .cook-later{max-width:850px;margin:0 auto;padding:20px;color:var(--recipe-ink,#25292e)}.cook-later h1{margin:15px 0 5px;font-family:Fraunces,Georgia,serif}.cook-later__list{display:grid;gap:12px;margin-top:24px}.cook-later__item{display:flex;align-items:center;justify-content:space-between;gap:20px;padding:18px;border:1px solid var(--recipe-line,#d0d8d0);border-radius:14px;background:var(--recipe-surface,#fff)}.cook-later__item h2{margin:0;font-size:1.15rem}.cook-later__item p{margin:6px 0}.cook-later__item small{color:var(--recipe-muted,#687178)}.cook-later__item button{min-height:44px;padding:8px 14px;border:1px solid #b94a55;border-radius:9px;background:transparent;color:#a12435;cursor:pointer}body[data-theme=dark] .cook-later__item button{color:#ffb3bb}body[data-theme=dark] .recipes-saved-badge{background:#294d38;color:#b7e8c5}@media(max-width:600px){.cook-later__item{align-items:flex-start;flex-direction:column}}
body[data-theme=dark] .cook-later{--recipe-ink:#eaf0ea;--recipe-muted:#afbbb2;--recipe-surface:#202a23;--recipe-line:#435046}body[data-theme=dark] .cook-later a{color:#a7d9b6} body[data-theme=dark] .cook-later{--recipe-ink:#eaf0ea;--recipe-muted:#afbbb2;--recipe-surface:#202a23;--recipe-line:#435046}body[data-theme=dark] .cook-later a{color:#a7d9b6}
/* Recipe photo upload controls */
.recipe-photo-upload{min-width:0}.recipe-photo-upload .recipes-photo-placeholder{position:relative;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:7px;height:220px;padding:20px;border:2px dashed #719d7d;border-radius:14px;color:#24573b;background:#e5f1e8;text-align:center;cursor:pointer;font-family:inherit;transition:border-color .15s,background .15s}.recipe-photo-upload__icon{display:grid;place-items:center;width:42px;height:42px;border-radius:50%;background:#d0e6d6;font-size:1.5rem;font-weight:700}.recipe-photo-upload .recipes-photo-placeholder strong{font-size:1rem}.recipe-photo-upload .recipes-photo-placeholder span:last-of-type{max-width:220px;font-size:.77rem;line-height:1.4}.recipe-photo-upload .recipes-photo-placeholder:hover,.recipe-photo-upload .recipes-photo-placeholder.is-dragging{border-color:#235943;background:#d9ebdf}.recipe-photo-upload .recipes-photo-placeholder:focus-within,.recipe-photo-editor__zone:focus-within{outline:3px solid #a44cbe;outline-offset:3px}.recipe-photo-upload input[type=file],.recipe-photo-editor input[type=file]{position:absolute;width:1px;height:1px;opacity:0;overflow:hidden}.recipe-photo-submit{margin-top:8px;min-height:40px;padding:7px 12px;border:0;border-radius:8px;color:#fff;background:#235943;cursor:pointer}.recipe-photo-submit[hidden]{display:none}.recipe-photo-upload__status{display:block;margin-top:6px;color:var(--recipe-muted);font-size:.75rem}
.recipes-photo-field-label{display:block;margin-bottom:6px;font-size:.81rem;font-weight:700}.recipe-photo-editor{position:relative;max-width:490px}.recipe-photo-editor__zone{position:relative;display:grid;place-items:center;min-height:225px;overflow:hidden;border:2px dashed #719d7d;border-radius:14px;background:#e5f1e8;color:#24573b;text-align:center;cursor:pointer}.recipe-photo-editor__zone.is-dragging,.recipe-photo-editor__zone:hover{border-color:#235943;background:#d9ebdf}.recipe-photo-editor__zone img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}.recipe-photo-editor__zone img[hidden]{display:none}.recipe-photo-editor__prompt{z-index:1;max-width:260px;padding:10px 16px;border-radius:10px;background:rgba(255,255,255,.88);font-size:.9rem;font-weight:700}.recipe-photo-editor__prompt small{display:block;margin-top:4px;font-weight:400}.recipe-photo-editor__remove{position:absolute;z-index:2;top:10px;right:10px;display:grid;place-items:center;width:36px;height:36px;border:0;border-radius:50%;color:#fff;background:#223029;font-size:1.45rem;line-height:1;cursor:pointer}.recipe-photo-editor__remove[hidden]{display:none}.recipe-photo-editor__remove:focus-visible{outline:3px solid #a44cbe;outline-offset:3px}.recipe-photo-editor__status{min-height:1.2em;margin:7px 0 0;color:var(--recipe-muted);font-size:.78rem}.recipe-photo-editor__checkbox[hidden]{display:none}body[data-theme=dark] .recipe-photo-upload .recipes-photo-placeholder,body[data-theme=dark] .recipe-photo-editor__zone{color:#c7e8cf;background:#314d39;border-color:#79a889}body[data-theme=dark] .recipe-photo-upload .recipes-photo-placeholder:hover,body[data-theme=dark] .recipe-photo-editor__zone:hover,body[data-theme=dark] .recipe-photo-editor__zone.is-dragging{background:#3a6246}body[data-theme=dark] .recipe-photo-upload__icon{background:#446f50}body[data-theme=dark] .recipe-photo-editor__prompt{color:#24372a}
.recipes-field .recipe-photo-editor__zone{display:grid;margin:0;align-items:center;justify-items:center}
.recipes-field label.recipe-photo-editor__zone{display:grid;margin:0;align-items:center;justify-items:center}
.recipe-photo-editor__prompt small,body[data-theme=dark] .recipe-photo-editor__prompt small{color:#415c4b}
+3 -3
View File
@@ -1,13 +1,13 @@
{% extends 'planner/base.html' %}{% load static %} {% extends 'planner/base.html' %}{% load static %}
{% block title %}{% if creating %}New recipe{% else %}Edit {{ recipe.title }}{% endif %} · Tasknest{% endblock %} {% block title %}{% if creating %}New recipe{% else %}Edit {{ recipe.title }}{% endif %} · Tasknest{% endblock %}
{% block page_class %}recipes-page-content{% endblock %} {% block page_class %}recipes-page-content{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'recipes/vendor/toastui-editor.min.css' %}"><link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=4"> {% block content %}<link rel="stylesheet" href="{% static 'recipes/vendor/toastui-editor.min.css' %}"><link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=11">
<div class="recipes-layout recipes-layout--form"><header class="recipes-form-header"><a href="{% if creating %}{% url 'recipes:list' %}{% else %}{% url 'recipes:detail' recipe.api_id %}{% endif %}">← Back to recipes</a><h1>{% if creating %}New recipe{% else %}Edit recipe{% endif %}</h1><p>Keep ingredients structured and instructions in Markdown.</p></header> <div class="recipes-layout recipes-layout--form"><header class="recipes-form-header"><a href="{% if creating %}{% url 'recipes:list' %}{% else %}{% url 'recipes:detail' recipe.api_id %}{% endif %}">← Back to recipes</a><h1>{% if creating %}New recipe{% else %}Edit recipe{% endif %}</h1><p>Keep ingredients structured and instructions in Markdown.</p></header>
<form method="post" enctype="multipart/form-data" class="recipes-edit-card" data-recipe-form data-autosave-url="{% if creating %}{% url 'recipes:autosave-new' %}{% else %}{% url 'recipes:autosave' recipe.api_id %}{% endif %}"{% if creating %} data-draft-id="{{ new_draft_id }}"{% endif %}>{% csrf_token %} <form method="post" enctype="multipart/form-data" class="recipes-edit-card" data-recipe-form data-autosave-url="{% if creating %}{% url 'recipes:autosave-new' %}{% else %}{% url 'recipes:autosave' recipe.api_id %}{% endif %}"{% if creating %} data-draft-id="{{ new_draft_id }}"{% endif %}>{% csrf_token %}
{% if creating %}<input type="hidden" name="draft_id" value="{{ new_draft_id }}">{% endif %} {% if creating %}<input type="hidden" name="draft_id" value="{{ new_draft_id }}">{% endif %}
{% if form.non_field_errors %}<div class="recipes-form-error" role="alert">{{ form.non_field_errors }}</div>{% endif %} {% if form.non_field_errors %}<div class="recipes-form-error" role="alert">{{ form.non_field_errors }}</div>{% endif %}
<section><h2>Recipe details</h2><div class="recipes-form-grid">{% for field in form %}{% if field.name == 'markdown_revision' %}{{ field }}{% elif field.name != 'remove_photo' %}<div class="recipes-field recipes-field--{{ field.name }}"><label for="{{ field.id_for_label }}">{{ field.label }}</label>{{ field }}{% if field.name == 'instructions_markdown' or field.name == 'notes_markdown' %}<div class="recipes-markdown-editor" data-markdown-editor="{{ field.name }}" aria-label="{{ field.label }} editor"></div>{% endif %}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{% if field.errors %}<div class="recipes-form-error" role="alert">{{ field.errors }}</div>{% endif %}</div>{% endif %}{% endfor %}{% if recipe.photo %}<div class="recipes-field recipes-field--remove_photo"><img src="{% url 'recipes:photo' recipe.api_id %}" alt="Current recipe photo" class="recipes-current-photo"><label class="recipes-checkbox">{{ form.remove_photo }} Remove current photo</label></div>{% endif %}</div></section> <section><h2>Recipe details</h2><div class="recipes-form-grid">{% for field in form %}{% if field.name == 'markdown_revision' %}{{ field }}{% elif field.name == 'photo' %}<div class="recipes-field recipes-field--photo"><span class="recipes-photo-field-label">Recipe photo</span><div class="recipe-photo-editor" data-photo-editor><label class="recipe-photo-editor__zone" for="{{ field.id_for_label }}">{% if existing_photo %}<img src="{% url 'recipes:photo' recipe.api_id %}" alt="Current recipe photo" data-photo-preview>{% else %}<img alt="Selected recipe photo preview" data-photo-preview hidden>{% endif %}<span class="recipe-photo-editor__prompt" data-photo-prompt>{% if existing_photo %}Click or drop to replace photo{% else %}Click or drop a photo here{% endif %}<small>JPEG, PNG or WebP · up to 5 MB</small></span>{{ field }}</label><button type="button" class="recipe-photo-editor__remove" data-photo-remove aria-label="Remove current recipe photo"{% if not existing_photo %} hidden{% endif %}>×</button></div><label class="recipes-checkbox recipe-photo-editor__checkbox" hidden>{{ form.remove_photo }} Remove current photo on save</label><p class="recipe-photo-editor__status" data-photo-edit-status role="status" aria-live="polite"></p>{% if field.errors %}<div class="recipes-form-error" role="alert">{{ field.errors }}</div>{% endif %}</div>{% elif field.name != 'remove_photo' %}<div class="recipes-field recipes-field--{{ field.name }}"><label for="{{ field.id_for_label }}">{{ field.label }}</label>{{ field }}{% if field.name == 'instructions_markdown' or field.name == 'notes_markdown' %}<div class="recipes-markdown-editor" data-markdown-editor="{{ field.name }}" aria-label="{{ field.label }} editor"></div>{% endif %}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{% if field.errors %}<div class="recipes-form-error" role="alert">{{ field.errors }}</div>{% endif %}</div>{% endif %}{% endfor %}</div></section>
<section><div class="recipes-section-heading"><div><h2>Ingredients</h2><p>Add measured ingredients now; product matching can be refined later.</p></div><button type="button" class="recipes-outline-button" data-add-ingredient>+ Add ingredient</button></div>{{ ingredients.management_form }}{% if ingredients.non_form_errors %}<div class="recipes-form-error" role="alert">{{ ingredients.non_form_errors }}</div>{% endif %}<div class="recipes-ingredient-forms" data-ingredient-forms>{% for ingredient in ingredients %}{% include 'recipes/ingredient_row.html' %}{% endfor %}</div><template id="recipe-empty-ingredient">{% with ingredient=ingredients.empty_form %}{% include 'recipes/ingredient_row.html' %}{% endwith %}</template></section> <section><div class="recipes-section-heading"><div><h2>Ingredients</h2><p>Add measured ingredients now; product matching can be refined later.</p></div><button type="button" class="recipes-outline-button" data-add-ingredient>+ Add ingredient</button></div>{{ ingredients.management_form }}{% if ingredients.non_form_errors %}<div class="recipes-form-error" role="alert">{{ ingredients.non_form_errors }}</div>{% endif %}<div class="recipes-ingredient-forms" data-ingredient-forms>{% for ingredient in ingredients %}{% include 'recipes/ingredient_row.html' %}{% endfor %}</div><template id="recipe-empty-ingredient">{% with ingredient=ingredients.empty_form %}{% include 'recipes/ingredient_row.html' %}{% endwith %}</template></section>
<section><div class="recipes-section-heading"><div><h2>Subrecipes</h2><p>Include an independently editable recipe as a component.</p></div><button type="button" class="recipes-outline-button" data-add-subrecipe>+ Add subrecipe</button></div>{{ subrecipes.management_form }}{% if subrecipes.non_form_errors %}<div class="recipes-form-error" role="alert">{{ subrecipes.non_form_errors }}</div>{% endif %}<div class="recipes-ingredient-forms" data-subrecipe-forms>{% for subrecipe in subrecipes %}{% include 'recipes/subrecipe_row.html' %}{% endfor %}</div><template id="recipe-empty-subrecipe">{% with subrecipe=subrecipes.empty_form %}{% include 'recipes/subrecipe_row.html' %}{% endwith %}</template></section> <section><div class="recipes-section-heading"><div><h2>Subrecipes</h2><p>Include an independently editable recipe as a component.</p></div><button type="button" class="recipes-outline-button" data-add-subrecipe>+ Add subrecipe</button></div>{{ subrecipes.management_form }}{% if subrecipes.non_form_errors %}<div class="recipes-form-error" role="alert">{{ subrecipes.non_form_errors }}</div>{% endif %}<div class="recipes-ingredient-forms" data-subrecipe-forms>{% for subrecipe in subrecipes %}{% include 'recipes/subrecipe_row.html' %}{% endfor %}</div><template id="recipe-empty-subrecipe">{% with subrecipe=subrecipes.empty_form %}{% include 'recipes/subrecipe_row.html' %}{% endwith %}</template></section>
<div class="recipes-form-actions"><button type="submit" class="button">Save recipe</button><a href="{% if creating %}{% url 'recipes:list' %}{% else %}{% url 'recipes:detail' recipe.api_id %}{% endif %}">Cancel</a><span class="recipes-save-status" data-save-status role="status" aria-live="polite">{% if creating %}Add a title to start autosave.{% else %}Saved{% endif %}</span></div> <div class="recipes-form-actions"><button type="submit" class="button">Save recipe</button><a href="{% if creating %}{% url 'recipes:list' %}{% else %}{% url 'recipes:detail' recipe.api_id %}{% endif %}">Cancel</a><span class="recipes-save-status" data-save-status role="status" aria-live="polite">{% if creating %}Add a title to start autosave.{% else %}Saved{% endif %}</span></div>
</form></div><script defer src="{% static 'recipes/vendor/toastui-editor-all.min.js' %}"></script><script defer src="{% static 'recipes/editor-adapter.js' %}?v=4"></script><script defer src="{% static 'recipes/form.js' %}?v=5"></script>{% endblock %} </form></div><script defer src="{% static 'recipes/vendor/toastui-editor-all.min.js' %}"></script><script defer src="{% static 'recipes/editor-adapter.js' %}?v=4"></script><script defer src="{% static 'recipes/form.js' %}?v=6"></script><script defer src="{% static 'recipes/photo_upload.js' %}?v=1"></script>{% endblock %}
+3 -3
View File
@@ -2,7 +2,7 @@
{% block title %}Recipes · Tasknest{% endblock %} {% block title %}Recipes · Tasknest{% endblock %}
{% block page_class %}recipes-page-content{% endblock %} {% block page_class %}recipes-page-content{% endblock %}
{% block content %} {% block content %}
<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=7"> <link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=8">
<div class="recipes-layout {% if explicit_detail %}recipes-layout--detail{% else %}recipes-layout--list{% endif %}"> <div class="recipes-layout {% if explicit_detail %}recipes-layout--detail{% else %}recipes-layout--list{% endif %}">
<aside class="recipes-browser" aria-label="Recipe browser"> <aside class="recipes-browser" aria-label="Recipe browser">
<div class="recipes-browser__heading"> <div class="recipes-browser__heading">
@@ -40,7 +40,7 @@
{% if selected %} {% if selected %}
<div class="recipes-detail__top"><a class="recipes-back" href="{% url 'recipes:list' %}">← Back to recipes</a><div class="recipes-detail__top-actions"><form method="post" action="{% url 'recipes:favourite' selected.api_id %}">{% csrf_token %}<button type="submit" class="recipes-heart" aria-label="{% if selected.is_favourite %}Remove {{ selected.title }} from favourites{% else %}Add {{ selected.title }} to favourites{% endif %}" aria-pressed="{% if selected.is_favourite %}true{% else %}false{% endif %}">{% if selected.is_favourite %}♥{% else %}♡{% endif %}</button></form><a class="recipes-outline-button" href="{% url 'recipes:edit' selected.api_id %}">Edit</a></div></div> <div class="recipes-detail__top"><a class="recipes-back" href="{% url 'recipes:list' %}">← Back to recipes</a><div class="recipes-detail__top-actions"><form method="post" action="{% url 'recipes:favourite' selected.api_id %}">{% csrf_token %}<button type="submit" class="recipes-heart" aria-label="{% if selected.is_favourite %}Remove {{ selected.title }} from favourites{% else %}Add {{ selected.title }} to favourites{% endif %}" aria-pressed="{% if selected.is_favourite %}true{% else %}false{% endif %}">{% if selected.is_favourite %}♥{% else %}♡{% endif %}</button></form><a class="recipes-outline-button" href="{% url 'recipes:edit' selected.api_id %}">Edit</a></div></div>
<div class="recipes-hero"> <div class="recipes-hero">
{% if selected.photo %}<img src="{% url 'recipes:photo' selected.api_id %}" alt="Photo of {{ selected.title }}">{% else %}<div class="recipes-photo-placeholder" role="img" aria-label="No recipe photo yet"><span>No photo yet</span></div>{% endif %} {% if selected.photo %}<img src="{% url 'recipes:photo' selected.api_id %}" alt="Photo of {{ selected.title }}">{% else %}<form class="recipe-photo-upload" method="post" enctype="multipart/form-data" action="{% url 'recipes:photo-upload' selected.api_id %}" data-photo-upload>{% csrf_token %}<label class="recipes-photo-placeholder" for="recipe-detail-photo"><span class="recipe-photo-upload__icon" aria-hidden="true">↑</span><strong>Add a recipe photo</strong><span>Click or drop a JPEG, PNG or WebP image</span><input id="recipe-detail-photo" name="photo" type="file" accept="image/jpeg,image/png,image/webp" required></label><button class="recipe-photo-submit" type="submit">Upload photo</button><span class="recipe-photo-upload__status" data-photo-status role="status" aria-live="polite"></span></form>{% endif %}
<div class="recipes-hero__copy"><p class="recipes-eyebrow">{% if selected.status == 'draft' %}Draft recipe{% else %}Recipe{% endif %}</p><h2>{{ selected.title }}</h2><p class="recipes-hero__meta">{{ selected.total_minutes }} min total · {{ selected.default_servings|floatformat:-2 }} servings</p><div class="recipes-chips">{% if selected.category %}<span>{{ selected.category }}</span>{% endif %}{% for value in selected.tags %}<span>{{ value }}</span>{% endfor %}</div>{% if selected.description %}<p class="recipes-hero__description">{{ selected.description }}</p>{% endif %}</div> <div class="recipes-hero__copy"><p class="recipes-eyebrow">{% if selected.status == 'draft' %}Draft recipe{% else %}Recipe{% endif %}</p><h2>{{ selected.title }}</h2><p class="recipes-hero__meta">{{ selected.total_minutes }} min total · {{ selected.default_servings|floatformat:-2 }} servings</p><div class="recipes-chips">{% if selected.category %}<span>{{ selected.category }}</span>{% endif %}{% for value in selected.tags %}<span>{{ value }}</span>{% endfor %}</div>{% if selected.description %}<p class="recipes-hero__description">{{ selected.description }}</p>{% endif %}</div>
</div> </div>
<form class="recipes-serving-form" method="get" action="{% url 'recipes:detail' selected.api_id %}"><label for="recipe-servings">Servings</label><input id="recipe-servings" type="number" name="servings" min="0.01" max="99999.99" step="0.01" value="{{ analysis.servings|floatformat:-2 }}"><label class="recipes-checkbox"><input type="checkbox" name="optional" value="1"{% if analysis.include_optional %} checked{% endif %}> Include optional ingredients</label><button type="submit" class="recipes-outline-button">Update</button></form> <form class="recipes-serving-form" method="get" action="{% url 'recipes:detail' selected.api_id %}"><label for="recipe-servings">Servings</label><input id="recipe-servings" type="number" name="servings" min="0.01" max="99999.99" step="0.01" value="{{ analysis.servings|floatformat:-2 }}"><label class="recipes-checkbox"><input type="checkbox" name="optional" value="1"{% if analysis.include_optional %} checked{% endif %}> Include optional ingredients</label><button type="submit" class="recipes-outline-button">Update</button></form>
@@ -63,5 +63,5 @@
<section class="recipes-panel"><h3>Actions</h3><a class="recipes-action" href="{% url 'recipes:edit' selected.api_id %}">Edit recipe</a><form method="post" action="{% url 'recipes:create-variation' selected.api_id %}" class="recipes-action-form">{% csrf_token %}<button type="submit" class="recipes-action">Create variation</button></form>{% if last_use %}<form method="post" action="{% url 'recipes:stock-undo' last_use.pk %}" class="recipes-action-form">{% csrf_token %}<button type="submit" class="recipes-action">Undo last inventory use</button></form>{% endif %}<a class="recipes-action recipes-action--danger" href="{% url 'recipes:delete' selected.api_id %}">Delete recipe</a></section> <section class="recipes-panel"><h3>Actions</h3><a class="recipes-action" href="{% url 'recipes:edit' selected.api_id %}">Edit recipe</a><form method="post" action="{% url 'recipes:create-variation' selected.api_id %}" class="recipes-action-form">{% csrf_token %}<button type="submit" class="recipes-action">Create variation</button></form>{% if last_use %}<form method="post" action="{% url 'recipes:stock-undo' last_use.pk %}" class="recipes-action-form">{% csrf_token %}<button type="submit" class="recipes-action">Undo last inventory use</button></form>{% endif %}<a class="recipes-action recipes-action--danger" href="{% url 'recipes:delete' selected.api_id %}">Delete recipe</a></section>
</aside>{% endif %} </aside>{% endif %}
</div> </div>
<script src="{% static 'planner/responsive_filters.js' %}?v=1" defer></script> <script src="{% static 'planner/responsive_filters.js' %}?v=1" defer></script><script src="{% static 'recipes/photo_upload.js' %}?v=1" defer></script>
{% endblock %} {% endblock %}
+24
View File
@@ -99,6 +99,30 @@ class RecipeWebTests(TestCase):
self.client.force_login(self.other) self.client.force_login(self.other)
self.assertEqual(self.client.get(photo_url).status_code, 404) self.assertEqual(self.client.get(photo_url).status_code, 404)
def test_detail_photo_drop_zone_upload_validates_and_scopes(self):
recipe = Recipe.objects.create(owner=self.user, title='Photo target')
image = BytesIO()
Image.new('RGB', (2, 2), '#217857').save(image, format='PNG')
url = reverse('recipes:photo-upload', args=[recipe.api_id])
with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
self.assertContains(self.client.get(reverse('recipes:detail', args=[recipe.api_id])),
'Add a recipe photo')
self.assertEqual(self.client.get(url).status_code, 405)
self.assertEqual(self.client.post(url, {'photo': SimpleUploadedFile(
'bad.png', b'not an image', content_type='image/png')}).status_code, 302)
recipe.refresh_from_db()
self.assertFalse(recipe.photo)
response = self.client.post(url, {'photo': SimpleUploadedFile(
'good.png', image.getvalue(), content_type='image/png')})
self.assertEqual(response.status_code, 302)
recipe.refresh_from_db()
self.assertTrue(recipe.photo)
self.assertContains(self.client.get(reverse('recipes:detail', args=[recipe.api_id])),
'Photo of Photo target')
self.client.force_login(self.other)
self.assertEqual(self.client.post(url, {'photo': SimpleUploadedFile(
'other.png', image.getvalue(), content_type='image/png')}).status_code, 404)
def test_markdown_round_trip_and_safe_rendering(self): def test_markdown_round_trip_and_safe_rendering(self):
source = '# Dinner\n\n- [x] Prepare\n- [ ] Cook\n\n**Ready** <script>alert(1)</script> [bad](javascript:alert(1))' source = '# Dinner\n\n- [x] Prepare\n- [ ] Cook\n\n**Ready** <script>alert(1)</script> [bad](javascript:alert(1))'
recipe = Recipe.objects.create(owner=self.user, title='Dinner', instructions_markdown=source) recipe = Recipe.objects.create(owner=self.user, title='Dinner', instructions_markdown=source)
+1
View File
@@ -17,6 +17,7 @@ urlpatterns = [
path('new/autosave/', views.autosave_new, name='autosave-new'), path('new/autosave/', views.autosave_new, name='autosave-new'),
path('<uuid:identifier>/', views.detail, name='detail'), path('<uuid:identifier>/', views.detail, name='detail'),
path('<uuid:identifier>/edit/', views.edit, name='edit'), path('<uuid:identifier>/edit/', views.edit, name='edit'),
path('<uuid:identifier>/photo/upload/', views.photo_upload, name='photo-upload'),
path('<uuid:identifier>/cook/', views.cook, name='cook'), path('<uuid:identifier>/cook/', views.cook, name='cook'),
path('<uuid:identifier>/cook/finish/', views.cook_finish, name='cook-finish'), path('<uuid:identifier>/cook/finish/', views.cook_finish, name='cook-finish'),
path('<uuid:identifier>/autosave/', views.autosave, name='autosave'), path('<uuid:identifier>/autosave/', views.autosave, name='autosave'),
+26 -1
View File
@@ -2,6 +2,7 @@ import json
import uuid import uuid
from django.conf import settings from django.conf import settings
from django.core.exceptions import ValidationError
from django.contrib import messages from django.contrib import messages
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
@@ -17,7 +18,7 @@ from food.models import MealType
from PIL import Image from PIL import Image
from .forms import (RecipeForm, RecipeIngredientFormSet, RecipeSubrecipeFormSet, from .forms import (RecipeForm, RecipeIngredientFormSet, RecipeSubrecipeFormSet,
RecipeSubstitutionForm) RecipeSubstitutionForm, validate_recipe_photo)
from .models import (CookLater, Recipe, RecipeIngredient, RecipeIngredientSubstitution, from .models import (CookLater, Recipe, RecipeIngredient, RecipeIngredientSubstitution,
RecipeSelection, RecipeSubrecipe, RecipeUse) RecipeSelection, RecipeSubrecipe, RecipeUse)
from .services import cook_later from .services import cook_later
@@ -364,6 +365,7 @@ def _edit(request, recipe=None, allow_draft_resume=False):
return render(request, 'recipes/form.html', { return render(request, 'recipes/form.html', {
'form': form, 'ingredients': ingredients, 'subrecipes': subrecipes, 'recipe': recipe, 'form': form, 'ingredients': ingredients, 'subrecipes': subrecipes, 'recipe': recipe,
'creating': creating, 'new_draft_id': recipe.api_id if creating else None, 'creating': creating, 'new_draft_id': recipe.api_id if creating else None,
'existing_photo': bool(old_photo),
}) })
@@ -389,6 +391,29 @@ def edit(request, identifier):
return _edit(request, get_object_or_404(_owned(request.user), api_id=identifier)) return _edit(request, get_object_or_404(_owned(request.user), api_id=identifier))
@login_required
@require_POST
def photo_upload(request, identifier):
recipe = get_object_or_404(_owned(request.user), api_id=identifier)
uploaded = request.FILES.get('photo')
if uploaded is None:
messages.error(request, 'Choose a photo to upload.')
return redirect('recipes:detail', identifier=identifier)
try:
validate_recipe_photo(uploaded)
except ValidationError as exc:
messages.error(request, exc.messages[0])
return redirect('recipes:detail', identifier=identifier)
old_name = recipe.photo.name if recipe.photo else ''
storage = recipe.photo.storage
recipe.photo = uploaded
recipe.save(update_fields=('photo', 'updated_at'))
if old_name and old_name != recipe.photo.name:
transaction.on_commit(lambda: storage.delete(old_name))
messages.success(request, 'Recipe photo uploaded.')
return redirect('recipes:detail', identifier=identifier)
@login_required @login_required
@require_POST @require_POST
def autosave(request, identifier): def autosave(request, identifier):