from django import forms from .models import FoodLogEntry, FoodProduct, MealType class ManualFoodForm(forms.ModelForm): 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', } 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 class FoodLogForm(forms.ModelForm): 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 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