from django import forms from django.forms import BaseInlineFormSet, inlineformset_factory from django.core.files.uploadedfile import UploadedFile from PIL import Image, UnidentifiedImageError from food.models import FoodProduct from .models import Recipe, RecipeIngredient, RecipeSubrecipe class RecipeForm(forms.ModelForm): markdown_revision = forms.IntegerField(min_value=0, widget=forms.HiddenInput) tags_text = forms.CharField(required=False, label='Tags', help_text='Separate tags with commas.') remove_photo = forms.BooleanField(required=False, label='Remove current photo') class Meta: model = Recipe fields = ('title', 'description', 'category', 'preparation_minutes', 'cooking_minutes', 'default_servings', 'status', 'parent', 'instructions_markdown', 'notes_markdown', 'photo') labels = {'instructions_markdown': 'Instructions (Markdown)', 'notes_markdown': 'Personal notes (Markdown)', 'default_servings': 'Servings', 'parent': 'Variation of'} widgets = { 'description': forms.Textarea(attrs={'rows': 3}), 'instructions_markdown': forms.Textarea(attrs={'rows': 10}), 'notes_markdown': forms.Textarea(attrs={'rows': 4}), 'photo': forms.ClearableFileInput(attrs={'accept': 'image/jpeg,image/png,image/webp'}), 'preparation_minutes': forms.NumberInput(attrs={'min': 0}), 'cooking_minutes': forms.NumberInput(attrs={'min': 0}), 'default_servings': forms.NumberInput(attrs={'min': '.01', 'step': '.01'}), } def __init__(self, *args, user, **kwargs): super().__init__(*args, **kwargs) self.fields['markdown_revision'].initial = self.instance.markdown_revision self.fields['parent'].queryset = Recipe.objects.filter(owner=user).exclude(pk=self.instance.pk) if self.instance.pk: self.fields['tags_text'].initial = ', '.join(self.instance.tags) def clean_tags_text(self): tags = [tag.strip() for tag in self.cleaned_data['tags_text'].split(',') if tag.strip()] if len(tags) > 12 or any(len(tag) > 40 for tag in tags): raise forms.ValidationError('Use up to 12 tags of at most 40 characters each.') return list(dict.fromkeys(tags)) def clean_photo(self): photo = self.cleaned_data.get('photo') if not isinstance(photo, UploadedFile): return photo if photo.size > 5 * 1024 * 1024: raise forms.ValidationError('Choose an image smaller than 5 MB.') if photo.content_type not in ('image/jpeg', 'image/png', 'image/webp'): raise forms.ValidationError('Choose a JPEG, PNG, or WebP image.') try: image = Image.open(photo) if image.format not in ('JPEG', 'PNG', 'WEBP') or image.width * image.height > 25_000_000: raise forms.ValidationError('Choose a valid image smaller than 25 megapixels.') image.verify() except (UnidentifiedImageError, OSError): raise forms.ValidationError('Choose a valid JPEG, PNG, or WebP image.') from None finally: photo.seek(0) return photo def save(self, commit=True): recipe = super().save(commit=False) recipe.tags = self.cleaned_data['tags_text'] if commit: recipe.save() return recipe class RecipeIngredientForm(forms.ModelForm): class Meta: model = RecipeIngredient fields = ('name', 'quantity', 'unit', 'preparation_note', 'is_optional', 'inventory_product', 'nutrition_product', 'display_order') widgets = {'quantity': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}), 'display_order': forms.NumberInput(attrs={'min': 0})} class OwnedIngredientFormSet(BaseInlineFormSet): def __init__(self, *args, user, **kwargs): self.user = user super().__init__(*args, **kwargs) def add_fields(self, form, index): super().add_fields(form, index) products = FoodProduct.objects.filter(owner=self.user).order_by('product_name') for name in ('inventory_product', 'nutrition_product'): form.fields[name].queryset = products RecipeIngredientFormSet = inlineformset_factory( Recipe, RecipeIngredient, form=RecipeIngredientForm, formset=OwnedIngredientFormSet, extra=2, can_delete=True, ) class RecipeSubrecipeForm(forms.ModelForm): class Meta: model = RecipeSubrecipe fields = ('component', 'quantity', 'unit', 'note', 'display_order') widgets = {'quantity': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}), 'display_order': forms.NumberInput(attrs={'min': 0})} class OwnedSubrecipeFormSet(BaseInlineFormSet): def __init__(self, *args, user, **kwargs): self.user = user super().__init__(*args, **kwargs) def add_fields(self, form, index): super().add_fields(form, index) form.fields['component'].queryset = Recipe.objects.filter(owner=self.user).exclude(pk=self.instance.pk) RecipeSubrecipeFormSet = inlineformset_factory( Recipe, RecipeSubrecipe, form=RecipeSubrecipeForm, formset=OwnedSubrecipeFormSet, fk_name='recipe', extra=1, can_delete=True, )