Files
Django_TasksApp/main/food/forms.py
T
2026-10-11 20:46:55 +02:00

217 lines
12 KiB
Python

from django import forms
from decimal import Decimal
from .models import FoodLogEntry, FoodPortion, FoodProduct, KitchenInventoryItem
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 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')
labels = {'portion_label_snapshot': 'Portion label (optional)'}
widgets = {'amount': forms.NumberInput(attrs={'min': '0.001', 'step': '0.001'})}
def __init__(self, *args, product=None, **kwargs):
super().__init__(*args, **kwargs)
self.product = product or getattr(self.instance, 'product', None)
if self.product and self.product.pk:
self.fields['unit'].initial = self.product.base_unit
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
class FoodProductHydrationForm(forms.ModelForm):
class Meta:
model = FoodProduct
fields = ('is_beverage', 'hydration_enabled', 'hydration_factor')
labels = {'is_beverage': 'Count as a beverage',
'hydration_enabled': 'Include in hydration totals',
'hydration_factor': 'Fluid counting factor (0 to 1)'}
widgets = {'hydration_factor': forms.NumberInput(attrs={'min': 0, 'max': 1, 'step': '.001'})}
class InventoryItemForm(forms.ModelForm):
location_name = forms.CharField(max_length=100, label='Location', widget=forms.TextInput(attrs={'list': 'inventory-locations', 'autocomplete': 'off'}))
category_name = forms.CharField(max_length=100, required=False, label='My category', widget=forms.TextInput(attrs={'list': 'inventory-categories', 'autocomplete': 'off'}))
class Meta:
model = KitchenInventoryItem
fields = ('quantity', 'original_amount', 'inventory_unit', 'opened', 'best_before', 'notes')
widgets = {'quantity': forms.NumberInput(attrs={'min': 1, 'step': 1}),
'original_amount': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}),
'best_before': forms.DateInput(attrs={'type': 'date'}),
'notes': forms.Textarea(attrs={'rows': 2})}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['inventory_unit'] = forms.ChoiceField(required=False, label='Package unit',
choices=[('', 'Count only (unknown size)')] + [(unit, unit) for unit in
('mg', 'g', 'kg', 'ml', 'L', 'pieces', 'packs', 'portions')])
self.fields['original_amount'].label = 'Amount per package'
if self.instance.pk:
self.fields['location_name'].initial = self.instance.location.name
self.fields['category_name'].initial = self.instance.category.name if self.instance.category else ''
self.fields['inventory_unit'].initial = self.instance.inventory_unit
def clean(self):
data = super().clean()
if bool(data.get('original_amount')) != bool(data.get('inventory_unit')):
raise forms.ValidationError('Enter both package amount and unit, or leave both blank.')
if data.get('original_amount') and self.instance.remaining_amount is None:
self.instance.remaining_amount = data['original_amount']
if self.instance.pk and self.instance.original_amount and data.get('original_amount') != self.instance.original_amount:
raise forms.ValidationError('Existing package sizes cannot be changed after tracking starts.')
if self.instance.pk and self.instance.original_amount and data.get('inventory_unit') != self.instance.inventory_unit:
raise forms.ValidationError('Existing package units cannot be changed after tracking starts.')
if self.instance.pk and self.instance.original_amount and data.get('quantity') != 1:
raise forms.ValidationError('A tracked package has a quantity of one.')
return data
def clean_location_name(self):
value = ' '.join(self.cleaned_data['location_name'].split())
if not value:
raise forms.ValidationError('Enter a location.')
return value
def clean_category_name(self):
return ' '.join(self.cleaned_data['category_name'].split())
class InventoryManualProductForm(forms.ModelForm):
class Meta:
model = FoodProduct
fields = ('product_name', 'brand', 'barcode', 'package_quantity')
def __init__(self, *args, user=None, **kwargs):
super().__init__(*args, **kwargs)
self.user = user
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 products.')
return barcode