""" Barn Web App - A collection of web-apps for my family's personal use, including a recipe database. Copyright © 2023 Benjamin Stadlbauer This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. This program comes with a copy of the GNU Affero General Public License file at the root of this project. """ from django.forms import ModelForm, ValidationError, modelformset_factory, BooleanField from .models import Recipe, Version, Ingredient class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['title', 'slug'] class VersionForm(ModelForm): recipe_id: int = 0 def __init__(self, *args, **kwargs): placeholder = None if 'author_placeholder' in kwargs: placeholder = kwargs.pop('author_placeholder') super().__init__(*args, **kwargs) if placeholder: self.fields['author'].widget.attrs.update({'placeholder': placeholder}) class Meta: model = Version fields = ['label', 'slug', 'body', 'author', 'img'] def clean_slug(self): slug = self.cleaned_data['slug'] if 'slug' in self.changed_data and self.recipe_id: recipe = Recipe.objects.get(id=self.recipe_id) if recipe.versions.filter(slug=slug).count() > 0: # type: ignore raise ValidationError('A recipe version with this slug already exists.') return slug class IngredientForm(ModelForm): class Meta: model = Ingredient fields = ['text'] IngredientFormSet = modelformset_factory(Ingredient, fields=('text',), extra=1)