adding food logging, phase 5
This commit is contained in:
+105
-5
@@ -1,27 +1,70 @@
|
||||
from django import forms
|
||||
from decimal import Decimal
|
||||
|
||||
from .models import FoodLogEntry, FoodProduct, MealType
|
||||
from .models import FoodLogEntry, FoodPortion, FoodProduct
|
||||
|
||||
|
||||
class ManualFoodForm(forms.ModelForm):
|
||||
basis_amount = forms.DecimalField(min_value=Decimal('0.001'), max_digits=10, decimal_places=3,
|
||||
initial=100, label='Nutrition basis amount')
|
||||
class Meta:
|
||||
model = FoodProduct
|
||||
fields = ('product_name', 'brand', 'barcode', 'base_unit', 'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', 'fibre_100', 'sugars_100', 'salt_100')
|
||||
labels = {
|
||||
'energy_kcal_100': 'Calories per 100 g or ml',
|
||||
'carbohydrates_100': 'Carbohydrates per 100 g or ml',
|
||||
'protein_100': 'Protein per 100 g or ml',
|
||||
'fat_100': 'Fat per 100 g or ml',
|
||||
'energy_kcal_100': 'Calories for base quantity',
|
||||
'carbohydrates_100': 'Carbohydrates for base quantity',
|
||||
'protein_100': 'Protein for base quantity',
|
||||
'fat_100': 'Fat for base quantity',
|
||||
'fibre_100': 'Fibre for base quantity (optional)',
|
||||
'sugars_100': 'Sugars for base quantity (optional)',
|
||||
'salt_100': 'Salt for base quantity (optional)',
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.user = kwargs.pop('user', None)
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields['barcode'].required = False
|
||||
for field in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100'):
|
||||
self.fields[field].required = True
|
||||
|
||||
def clean_barcode(self):
|
||||
barcode = self.cleaned_data['barcode'].strip()
|
||||
if barcode and (not barcode.isascii() or not barcode.isdigit()):
|
||||
raise forms.ValidationError('Enter a numeric barcode.')
|
||||
if barcode and self.user and FoodProduct.objects.filter(owner=self.user, barcode=barcode).exists():
|
||||
raise forms.ValidationError('This barcode is already saved in your foods.')
|
||||
return barcode
|
||||
|
||||
def clean(self):
|
||||
data = super().clean()
|
||||
basis = data.get('basis_amount')
|
||||
if basis:
|
||||
factor = Decimal('100') / basis
|
||||
for name in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100',
|
||||
'fibre_100', 'sugars_100', 'salt_100'):
|
||||
value = data.get(name)
|
||||
if value is not None and value * factor > Decimal('9999999.999'):
|
||||
self.add_error(name, 'This amount is too large for the chosen base quantity.')
|
||||
return data
|
||||
|
||||
def save(self, commit=True):
|
||||
product = super().save(commit=False)
|
||||
factor = Decimal('100') / self.cleaned_data['basis_amount']
|
||||
for name in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100',
|
||||
'fibre_100', 'sugars_100', 'salt_100'):
|
||||
value = self.cleaned_data[name]
|
||||
setattr(product, name, (value * factor).quantize(Decimal('0.001')) if value is not None else None)
|
||||
if commit:
|
||||
product.save()
|
||||
return product
|
||||
|
||||
|
||||
class FoodLogForm(forms.ModelForm):
|
||||
portion = forms.ChoiceField(label='Portion', required=False)
|
||||
save_portion = forms.BooleanField(required=False, label='Save custom amount as a portion')
|
||||
new_portion_label = forms.CharField(max_length=100, required=False, label='New portion label')
|
||||
make_default = forms.BooleanField(required=False, label='Use this portion by default')
|
||||
|
||||
class Meta:
|
||||
model = FoodLogEntry
|
||||
fields = ('meal', 'amount', 'unit', 'portion_label_snapshot')
|
||||
@@ -33,9 +76,66 @@ class FoodLogForm(forms.ModelForm):
|
||||
self.product = product or getattr(self.instance, 'product', None)
|
||||
if self.product and self.product.pk:
|
||||
self.fields['unit'].initial = self.product.base_unit
|
||||
unit = self.product.base_unit
|
||||
choices = [('custom', 'Custom amount'), ('base', f'100 {unit}')]
|
||||
if self.product.serving_amount and self.product.serving_unit == unit:
|
||||
choices.append(('serving', f'Serving — {self.product.serving_amount:g} {unit}'))
|
||||
portions = list(FoodPortion.objects.filter(product=self.product, user=self.product.owner).order_by('label'))
|
||||
choices.extend((f'portion:{item.pk}', f'{item.label} — {item.amount:g} {item.unit}') for item in portions)
|
||||
self.fields['portion'].choices = choices
|
||||
self.portions = {str(item.pk): item for item in portions}
|
||||
default = next((item for item in portions if item.is_default), None)
|
||||
if default is None:
|
||||
last = self.product.log_entries.filter(user=self.product.owner).order_by('-created_at').first()
|
||||
default = next((item for item in portions if last and item.label == last.portion_label_snapshot and
|
||||
item.amount == last.amount and item.unit == last.unit), None)
|
||||
if self.instance.pk:
|
||||
selected = next((item for item in portions if item.label == self.instance.portion_label_snapshot and
|
||||
item.amount == self.instance.amount and item.unit == self.instance.unit), None)
|
||||
self.fields['portion'].initial = f'portion:{selected.pk}' if selected else 'custom'
|
||||
elif default:
|
||||
self.fields['portion'].initial = f'portion:{default.pk}'
|
||||
self.fields['amount'].initial = default.amount
|
||||
elif self.product.serving_amount and self.product.serving_unit == unit:
|
||||
self.fields['portion'].initial = 'serving'
|
||||
self.fields['amount'].initial = self.product.serving_amount
|
||||
else:
|
||||
self.fields['portion'].initial = 'base'
|
||||
self.fields['amount'].initial = 100
|
||||
self.fields['amount'].required = False
|
||||
|
||||
def clean_unit(self):
|
||||
unit = self.cleaned_data['unit']
|
||||
if self.product and unit != self.product.base_unit:
|
||||
raise forms.ValidationError('Use the same unit as the product nutrition basis.')
|
||||
return unit
|
||||
|
||||
def clean(self):
|
||||
data = super().clean()
|
||||
selected = data.get('portion') or 'custom'
|
||||
if not self.product or not selected:
|
||||
return data
|
||||
if selected == 'base':
|
||||
data['amount'], data['portion_label_snapshot'] = Decimal('100'), ''
|
||||
elif selected == 'serving':
|
||||
data['amount'], data['portion_label_snapshot'] = self.product.serving_amount, 'Serving'
|
||||
elif selected.startswith('portion:'):
|
||||
portion = self.portions.get(selected.partition(':')[2])
|
||||
if not portion:
|
||||
self.add_error('portion', 'Choose a valid portion.')
|
||||
else:
|
||||
data['amount'], data['portion_label_snapshot'] = portion.amount, portion.label
|
||||
elif selected == 'custom':
|
||||
if data.get('amount') is None or data['amount'] <= 0:
|
||||
self.add_error('amount', 'Enter an amount greater than zero.')
|
||||
if data.get('save_portion'):
|
||||
label = (data.get('new_portion_label') or '').strip()
|
||||
if not label:
|
||||
self.add_error('new_portion_label', 'Enter a label for the saved portion.')
|
||||
elif FoodPortion.objects.filter(user=self.product.owner, product=self.product, label=label).exists():
|
||||
self.add_error('new_portion_label', 'You already have a portion with this label.')
|
||||
else:
|
||||
data['portion_label_snapshot'] = label
|
||||
elif data.get('make_default'):
|
||||
self.add_error('make_default', 'Save the portion before making it the default.')
|
||||
return data
|
||||
|
||||
Reference in New Issue
Block a user