fixup! Add forms for adding recipes and versions

Add author name option
This commit is contained in:
Benjamin 2023-02-26 23:23:01 +01:00
parent 37f69e7364
commit adb67386af
3 changed files with 29 additions and 3 deletions

View file

@ -1,12 +1,14 @@
from django.forms import ModelForm, ValidationError, formset_factory
from django.forms import ModelForm, ValidationError, formset_factory, BooleanField
from .models import Recipe, Version, Ingredient
class VersionForm(ModelForm):
recipe_id: int
use_user_for_author = BooleanField(initial=True, label='I am the author', required=False)
class Meta:
model = Version
fields = ['label', 'slug', 'body']
fields = ['label', 'slug', 'body', 'author_name']
def clean_slug(self):
recipe = Recipe.objects.get(id=self.recipe_id)

View file

@ -15,6 +15,26 @@
</form>
<script>
let userIsAuthorCheckbox = document.querySelector("#id_version-use_user_for_author");
let authorNameValue = "";
function enableAuthorNameInput() {
let authorName = document.querySelector("#id_version-author_name")
if (userIsAuthorCheckbox.checked) {
authorName.setAttribute("disabled", "");
authorNameValue = authorName.value;
authorName.value = "";
} else {
authorName.removeAttribute("disabled");
authorName.value = authorNameValue;
}
}
enableAuthorNameInput();
userIsAuthorCheckbox.addEventListener('input', enableAuthorNameInput)
let firstIngredientDiv = document.querySelector("input[id^=id_ingredient][id$=text]").parentElement;
let addIngredientButton = document.querySelector("#add-ingredient");
let form = document.querySelector("#add-version-form");

View file

@ -51,7 +51,11 @@ def add_version(request, slug_recipe):
if version_form.is_valid() and ingredients_formset.is_valid():
version = version_form.save(commit=False)
version.author_user = request.user
if version_form.cleaned_data['use_user_for_author']:
version.author_user = request.user
version.author_name = ''
elif 'author_name' in version_form.cleaned_data:
version.author_name = version_form.cleaned_data['author_name']
version.recipe = recipe
version.save()