From efc2b1f39073c600ec5cddf51d2417bd220e50be Mon Sep 17 00:00:00 2001 From: Benjamin Date: Sat, 11 Mar 2023 19:17:19 +0100 Subject: [PATCH] Add forms --- recipes/forms.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 recipes/forms.py diff --git a/recipes/forms.py b/recipes/forms.py new file mode 100644 index 0000000..f02cf4d --- /dev/null +++ b/recipes/forms.py @@ -0,0 +1,37 @@ +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 + + 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'] + + def clean_slug(self): + slug = self.cleaned_data['slug'] + if 'slug' in self.changed_data: + 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)