Files
Django_TasksApp/main/food/forms.py
T

253 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from django import forms
from decimal import Decimal
import uuid
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)
portion_count = forms.IntegerField(label='How many portions', min_value=1, max_value=999,
required=False, initial=1)
inventory_package = forms.ChoiceField(label='Use inventory', 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, inventory_options=None, **kwargs):
super().__init__(*args, **kwargs)
self.product = product or getattr(self.instance, 'product', None)
self.fields['inventory_package'].choices = [('', 'Log without using inventory')] + (inventory_options or [])
if self.instance.pk and self.instance.created_via == 'recipe':
self.fields['unit'].choices = [('servings', 'servings')]
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.instance.pk and self.instance.created_via == 'recipe' and unit != 'servings':
raise forms.ValidationError('Recipe entries use servings.')
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()
if self.instance.pk and self.instance.created_via == 'recipe':
run = getattr(self.instance, 'recipe_cooking_run', None)
if run and data.get('amount') is not None and data['amount'] > run.prepared_servings:
self.add_error('amount', 'This portion exceeds the prepared servings.')
selected = data.get('portion') or 'custom'
count = data.get('portion_count') or 1
if not self.product or not selected:
return data
if selected == 'base':
data['amount'], data['portion_label_snapshot'] = Decimal('100') * count, ''
elif selected == 'serving':
data['amount'], data['portion_label_snapshot'] = self.product.serving_amount * count, f'{count} × serving' if count > 1 else '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 * count, f'{count} × {portion.label}' if count > 1 else 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():
try:
submission_id = uuid.UUID(self.data.get('submission_id', ''))
except (ValueError, TypeError, AttributeError):
submission_id = None
if not (submission_id and FoodLogEntry.objects.filter(user=self.product.owner,
api_id=submission_id).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 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 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