adding food logging, phase 4
This commit is contained in:
+2
-1
@@ -6,7 +6,7 @@ from .models import FoodLogEntry, FoodProduct, MealType
|
||||
class ManualFoodForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = FoodProduct
|
||||
fields = ('product_name', 'brand', 'base_unit', 'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', 'fibre_100', 'sugars_100', 'salt_100')
|
||||
fields = ('product_name', 'brand', 'barcode', 'base_unit', 'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', 'fibre_100', 'sugars_100', 'salt_100')
|
||||
labels = {
|
||||
'energy_kcal_100': 'Calories per 100 g or ml',
|
||||
'carbohydrates_100': 'Carbohydrates per 100 g or ml',
|
||||
@@ -16,6 +16,7 @@ class ManualFoodForm(forms.ModelForm):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields['barcode'].required = False
|
||||
for field in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100'):
|
||||
self.fields[field].required = True
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
.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}
|
||||
.food-tabs,.food-actions{display:flex;gap:.5rem;flex-wrap:wrap;margin:1rem 0}.food-tabs a{padding:.55rem .9rem;border-radius:2rem;border:1px solid currentColor;text-decoration:none}.food-tabs a[aria-current=page]{background:#62bd70;color:#111;border-color:#62bd70}.food-product-list a,.food-result-button{display:flex;align-items:center;gap:.8rem;width:100%;text-align:left}.food-product-list img{width:58px;height:58px;object-fit:contain;background:#fff;border-radius:.6rem}.food-product-list strong,.food-product-list small{display:block}.food-result-button{border:0;background:none;color:inherit;font:inherit;cursor:pointer;min-height:44px}.food-barcode-form{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap;margin:1rem 0}.food-barcode-form input{min-width:130px;flex:1}.food-attribution{font-size:.85rem;opacity:.8}
|
||||
.food-scanner{max-width:620px;margin:1.5rem auto 6rem}.food-scanner-header{display:flex;align-items:center;gap:1rem}.food-scanner-header a{display:grid;place-items:center;min-width:44px;min-height:44px;font-size:2rem;text-decoration:none}.food-camera-frame{position:relative;aspect-ratio:4/3;background:#111;border-radius:1rem;overflow:hidden}.food-camera-frame video{width:100%;height:100%;object-fit:cover}.food-scan-guide{position:absolute;inset:25% 10%;border:3px solid #62bd70;border-radius:.8rem;pointer-events:none}.food-mobile-switch{display:none}@media(max-width:760px){.food-mobile-switch{position:fixed;bottom:env(safe-area-inset-bottom,0px);left:50%;transform:translateX(-50%);display:flex;gap:.3rem;background:#222;color:#fff;padding:.35rem;border-radius:2rem;z-index:20;box-shadow:0 2px 15px #0008}.food-mobile-switch a,.food-mobile-switch span{display:grid;place-items:center;min-width:110px;min-height:44px;padding:.2rem 1rem;border-radius:2rem;color:inherit;text-decoration:none}.food-mobile-switch [aria-current=page]{background:#555}}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
(() => {
|
||||
const root = document.querySelector('[data-food-scanner]');
|
||||
if (!root) return;
|
||||
const video = root.querySelector('[data-scanner-video]');
|
||||
const status = root.querySelector('[data-scanner-status]');
|
||||
const startButton = root.querySelector('[data-scanner-start]');
|
||||
const stopButton = root.querySelector('[data-scanner-stop]');
|
||||
const form = root.querySelector('[data-scanner-form]');
|
||||
const input = root.querySelector('[data-scanner-barcode]');
|
||||
const formats = ['ean_13', 'ean_8', 'upc_a', 'upc_e', 'code_128'];
|
||||
let stream = null;
|
||||
let controls = null;
|
||||
let frame = null;
|
||||
let nativeTimeout = null;
|
||||
let generation = 0;
|
||||
let locked = false;
|
||||
let opening = false;
|
||||
let fallbackStarted = false;
|
||||
|
||||
const debug = (...args) => { if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') console.debug('[food:scanner]', ...args); };
|
||||
const tell = (message) => { status.textContent = message; };
|
||||
const stop = () => {
|
||||
generation += 1;
|
||||
if (frame !== null) cancelAnimationFrame(frame);
|
||||
frame = null;
|
||||
if (nativeTimeout !== null) clearTimeout(nativeTimeout);
|
||||
nativeTimeout = null;
|
||||
if (controls) controls.stop();
|
||||
controls = null;
|
||||
if (stream) { debug('stopping camera tracks'); stream.getTracks().forEach((track) => track.stop()); }
|
||||
stream = null;
|
||||
video.pause();
|
||||
video.srcObject = null;
|
||||
startButton.hidden = false;
|
||||
stopButton.hidden = true;
|
||||
opening = false;
|
||||
};
|
||||
const found = (value) => {
|
||||
const code = String(value || '').trim();
|
||||
if (locked || !/^[0-9]{6,64}$/.test(code)) return;
|
||||
locked = true;
|
||||
debug('detected', code);
|
||||
tell('Barcode found. Looking up product…');
|
||||
stop();
|
||||
input.value = code;
|
||||
form.requestSubmit();
|
||||
};
|
||||
const loadZXing = () => new Promise((resolve, reject) => {
|
||||
if (window.ZXingBrowser) return resolve(window.ZXingBrowser);
|
||||
const script = document.createElement('script');
|
||||
script.src = root.dataset.zxingUrl;
|
||||
script.onload = () => window.ZXingBrowser ? resolve(window.ZXingBrowser) : reject(new Error('Scanner library unavailable'));
|
||||
script.onerror = () => reject(new Error('Scanner library unavailable'));
|
||||
document.head.append(script);
|
||||
});
|
||||
const fallback = async (token) => {
|
||||
if (token !== generation || !stream || fallbackStarted) return;
|
||||
fallbackStarted = true;
|
||||
if (frame !== null) cancelAnimationFrame(frame);
|
||||
frame = null;
|
||||
if (nativeTimeout !== null) clearTimeout(nativeTimeout);
|
||||
nativeTimeout = null;
|
||||
debug('using ZXing fallback');
|
||||
tell('Scanning barcode…');
|
||||
try {
|
||||
const zxing = await loadZXing();
|
||||
if (token !== generation || !stream) return;
|
||||
const reader = new zxing.BrowserMultiFormatOneDReader();
|
||||
const active = await reader.decodeFromStream(stream, video, (result, error, scanControls) => {
|
||||
if (result) {
|
||||
controls = scanControls;
|
||||
found(result.getText());
|
||||
}
|
||||
});
|
||||
if (token !== generation || !stream) active.stop();
|
||||
else controls = active;
|
||||
} catch (error) {
|
||||
debug('fallback error', error);
|
||||
stop();
|
||||
tell('Scanner unavailable. Enter the barcode manually.');
|
||||
input.focus();
|
||||
}
|
||||
};
|
||||
const native = async (token) => {
|
||||
if (!('BarcodeDetector' in window)) return false;
|
||||
try {
|
||||
const supported = await window.BarcodeDetector.getSupportedFormats();
|
||||
const usable = formats.filter((format) => supported.includes(format));
|
||||
if (!usable.length || token !== generation) return false;
|
||||
debug('native BarcodeDetector available');
|
||||
const detector = new window.BarcodeDetector({ formats: usable });
|
||||
let failures = 0;
|
||||
const scan = async () => {
|
||||
if (token !== generation || locked || fallbackStarted) return;
|
||||
try {
|
||||
const hits = await detector.detect(video);
|
||||
if (token !== generation || locked || fallbackStarted) return;
|
||||
if (hits.length) { found(hits[0].rawValue); return; }
|
||||
} catch (error) {
|
||||
failures += 1;
|
||||
if (failures >= 3) { fallback(token); return; }
|
||||
}
|
||||
if (!fallbackStarted) frame = requestAnimationFrame(scan);
|
||||
};
|
||||
nativeTimeout = setTimeout(() => { if (token === generation && !locked) fallback(token); }, 12000);
|
||||
frame = requestAnimationFrame(scan);
|
||||
return true;
|
||||
} catch (error) { debug('native detector unavailable', error); return false; }
|
||||
};
|
||||
const open = async () => {
|
||||
if (opening || stream) return;
|
||||
locked = false;
|
||||
fallbackStarted = false;
|
||||
opening = true;
|
||||
const token = ++generation;
|
||||
startButton.hidden = true;
|
||||
tell('Requesting camera…');
|
||||
debug('requesting camera');
|
||||
try {
|
||||
if (!navigator.mediaDevices?.getUserMedia) throw new Error('Camera API unavailable');
|
||||
const acquired = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } } });
|
||||
if (token !== generation) { acquired.getTracks().forEach((track) => track.stop()); return; }
|
||||
stream = acquired;
|
||||
video.srcObject = stream;
|
||||
await video.play();
|
||||
if (token !== generation) return;
|
||||
opening = false;
|
||||
stopButton.hidden = false;
|
||||
tell('Scanning barcode…');
|
||||
if (!(await native(token))) await fallback(token);
|
||||
} catch (error) {
|
||||
debug('camera error', error);
|
||||
stop();
|
||||
tell('Camera unavailable or permission denied. Enter the barcode manually.');
|
||||
input.focus();
|
||||
}
|
||||
};
|
||||
startButton.addEventListener('click', open);
|
||||
stopButton.addEventListener('click', () => { stop(); tell('Camera is off.'); startButton.focus(); });
|
||||
form.addEventListener('submit', () => { locked = true; stop(); tell('Looking up product…'); });
|
||||
root.querySelector('[data-scanner-close]').addEventListener('click', stop);
|
||||
document.addEventListener('visibilitychange', () => { if (document.hidden) stop(); });
|
||||
window.addEventListener('pagehide', stop);
|
||||
})();
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 ZXing for JS
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
File diff suppressed because one or more lines are too long
@@ -41,9 +41,11 @@
|
||||
{% if item.image_url %}<img src="{{ item.image_url }}" alt="" loading="lazy">{% endif %}<span><strong>{{ item.product_name }}</strong>{% if item.brand %}<small>{{ item.brand }}</small>{% endif %}<small>{% if item.energy_kcal_100 is not None %}{{ item.energy_kcal_100|floatformat:0 }} kcal / 100 {{ item.base_unit }}{% else %}— kcal / 100 {{ item.base_unit }}{% endif %}</small></span>
|
||||
</a></li>{% empty %}<li>No foods in this list yet.</li>{% endfor %}</ul>
|
||||
<div class="food-actions"><a class="button" href="{% url 'food:manual' %}?date={{ day|date:'Y-m-d' }}&meal={{ meal }}">Create a food manually</a>
|
||||
<a class="button" href="{% url 'food:scanner' %}?date={{ day|date:'Y-m-d' }}&meal={{ meal }}">Scan barcode</a>
|
||||
<a class="button button--secondary" href="{% url 'food:external-search' %}?date={{ day|date:'Y-m-d' }}&meal={{ meal }}&q={{ query|urlencode }}">Search Open Food Facts</a></div>
|
||||
<form method="post" action="{% url 'food:import-product' %}" class="food-barcode-form">{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}"><label for="food-barcode">Barcode</label><input id="food-barcode" name="barcode" inputmode="numeric" pattern="[0-9]+" required><button class="button button--secondary" type="submit">Look up barcode</button></form>
|
||||
<p class="food-attribution">External product data from <a href="https://world.openfoodfacts.org/" rel="noopener noreferrer">Open Food Facts</a>.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if not product %}<nav class="food-mobile-switch" aria-label="Add food method"><span aria-current="page">Search</span><a href="{% url 'food:scanner' %}?date={{ day|date:'Y-m-d' }}&meal={{ meal }}">Barcode</a></nav>{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Product not found · Tasknest{% endblock %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}"><section class="food-form-page food-card"><h1>Product not found</h1><p>Barcode: <strong>{{ barcode }}</strong></p><p>You can enter this food yourself or scan another barcode.</p><div class="food-actions"><a class="button" href="{% url 'food:manual' %}?date={{ day|date:'Y-m-d' }}&meal={{ meal }}&barcode={{ barcode }}">Enter food manually</a><a class="button button--secondary" href="{% url 'food:scanner' %}?date={{ day|date:'Y-m-d' }}&meal={{ meal }}">Scan again</a></div></section>{% endblock %}
|
||||
@@ -0,0 +1,21 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Scan food barcode · Tasknest{% endblock %}
|
||||
{% block content %}
|
||||
<link rel="stylesheet" href="{% static 'food/food.css' %}">
|
||||
<div class="food-scanner" data-food-scanner data-zxing-url="{% static 'food/vendor/zxing-browser.min.js' %}">
|
||||
<header class="food-scanner-header"><a href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&meal={{ meal }}" data-scanner-close aria-label="Close barcode scanner">×</a><h1>Scan barcode</h1></header>
|
||||
<p>Point your camera at an EAN or UPC food barcode.</p>
|
||||
<div class="food-camera-frame"><video data-scanner-video autoplay muted playsinline aria-label="Camera preview"></video><div class="food-scan-guide" aria-hidden="true"></div></div>
|
||||
<p data-scanner-status role="status" aria-live="polite">Camera is off.</p>
|
||||
<button class="button" type="button" data-scanner-start>Start camera</button>
|
||||
<button class="button button--secondary" type="button" data-scanner-stop hidden>Stop camera</button>
|
||||
<form method="post" action="{% url 'food:import-product' %}" data-scanner-form class="food-barcode-form">
|
||||
{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}">
|
||||
<label for="scanner-barcode">Enter barcode manually</label><input id="scanner-barcode" data-scanner-barcode name="barcode" inputmode="numeric" pattern="[0-9]+" required>
|
||||
<button class="button button--secondary" type="submit">Look up barcode</button>
|
||||
</form>
|
||||
<p class="food-attribution">Product data from <a href="https://world.openfoodfacts.org/" rel="noopener noreferrer">Open Food Facts</a>.</p>
|
||||
</div>
|
||||
<nav class="food-mobile-switch" aria-label="Add food method"><a href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&meal={{ meal }}">Search</a><span aria-current="page">Barcode</span></nav>
|
||||
<script src="{% static 'food/scanner.js' %}" defer></script>
|
||||
{% endblock %}
|
||||
@@ -100,3 +100,21 @@ class OpenFoodFactsTests(TestCase):
|
||||
def test_http_timeout_raises_service_error(self, urlopen):
|
||||
with self.assertRaises(OpenFoodFactsError):
|
||||
OpenFoodFactsClient().get_product(SAMPLE['code'])
|
||||
|
||||
@patch.object(OpenFoodFactsClient, 'get_product', return_value=None)
|
||||
def test_unknown_barcode_offers_manual_entry_with_prefill(self, get_product):
|
||||
response = self.client.post(reverse('food:import-product'), {'barcode': SAMPLE['code'],
|
||||
'meal': 'breakfast', 'date': '2026-10-03'}, follow=True)
|
||||
self.assertContains(response, 'Product not found')
|
||||
self.assertContains(response, SAMPLE['code'])
|
||||
manual = self.client.get(reverse('food:manual'), {'barcode': SAMPLE['code'],
|
||||
'meal': 'breakfast', 'date': '2026-10-03'})
|
||||
self.assertContains(manual, f'value="{SAMPLE["code"]}"')
|
||||
|
||||
def test_scanner_requires_login_and_valid_meal(self):
|
||||
self.assertEqual(self.client.get(reverse('food:scanner'), {'meal': 'invalid'}).status_code, 400)
|
||||
response = self.client.get(reverse('food:scanner'), {'meal': 'dinner', 'date': '2026-10-03'})
|
||||
self.assertContains(response, 'data-food-scanner')
|
||||
self.assertContains(response, 'name="meal" value="dinner"')
|
||||
self.client.logout()
|
||||
self.assertEqual(self.client.get(reverse('food:scanner')).status_code, 302)
|
||||
|
||||
@@ -9,6 +9,8 @@ urlpatterns = [
|
||||
path('add/', views.add_food, name='add'),
|
||||
path('search/openfoodfacts/', views.external_search, name='external-search'),
|
||||
path('import/openfoodfacts/', views.import_product, name='import-product'),
|
||||
path('scan/', views.scanner, name='scanner'),
|
||||
path('not-found/', views.product_not_found, name='not-found'),
|
||||
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'),
|
||||
|
||||
+30
-3
@@ -1,5 +1,7 @@
|
||||
from decimal import Decimal
|
||||
import logging
|
||||
import re
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.http import HttpResponseBadRequest
|
||||
@@ -139,11 +141,33 @@ def import_product(request):
|
||||
messages.warning(request, f'{error} Recent, favourite, and saved products are still available.')
|
||||
return redirect(f"{reverse('food:add')}?date={day}&meal={meal}")
|
||||
if not product:
|
||||
messages.warning(request, 'Product not found. You can create it manually.')
|
||||
return redirect(f"{reverse('food:manual')}?date={day}&meal={meal}")
|
||||
return redirect(f"{reverse('food:not-found')}?{urlencode({'date': day.isoformat(), 'meal': meal, 'barcode': barcode})}")
|
||||
return redirect(f"{reverse('food:add')}?date={day}&meal={meal}&product={product.pk}")
|
||||
|
||||
|
||||
@login_required
|
||||
def scanner(request):
|
||||
day, error = _day(request)
|
||||
if error:
|
||||
return error
|
||||
meal = request.GET.get('meal') or MealType.BREAKFAST
|
||||
if meal not in MealType.values:
|
||||
return HttpResponseBadRequest('Invalid meal.')
|
||||
return render(request, 'food/scanner.html', {'day': day, 'meal': meal})
|
||||
|
||||
|
||||
@login_required
|
||||
def product_not_found(request):
|
||||
day, error = _day(request)
|
||||
if error:
|
||||
return error
|
||||
meal = request.GET.get('meal') or MealType.BREAKFAST
|
||||
barcode = request.GET.get('barcode', '').strip()
|
||||
if meal not in MealType.values or not re.fullmatch(r'[0-9]{1,64}', barcode):
|
||||
return HttpResponseBadRequest('Invalid barcode or meal.')
|
||||
return render(request, 'food/not_found.html', {'day': day, 'meal': meal, 'barcode': barcode})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def manual_food(request):
|
||||
@@ -153,7 +177,10 @@ def manual_food(request):
|
||||
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)
|
||||
barcode = request.GET.get('barcode', '').strip()
|
||||
if barcode and not re.fullmatch(r'[0-9]{1,64}', barcode):
|
||||
return HttpResponseBadRequest('Invalid barcode.')
|
||||
form = ManualFoodForm(request.POST or None, initial={'barcode': barcode})
|
||||
if request.method == 'POST' and form.is_valid():
|
||||
product = form.save(commit=False)
|
||||
product.owner = request.user
|
||||
|
||||
Reference in New Issue
Block a user