Merge pull request #2827 from hughrun/2571

Retain subjects and authors when new book form fails validation
This commit is contained in:
Mouse Reeve 2023-05-30 10:51:52 -07:00 committed by GitHub
commit ca3054fdac
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -45,6 +45,7 @@ class EditBook(View):
data = {"book": book, "form": form}
ensure_transient_values_persist(request, data)
if not form.is_valid():
ensure_transient_values_persist(request, data, add_author=True)
return TemplateResponse(request, "book/edit/edit_book.html", data)
data = add_authors(request, data)
@ -102,11 +103,13 @@ class CreateBook(View):
"authors": authors,
}
ensure_transient_values_persist(request, data)
if not form.is_valid():
ensure_transient_values_persist(request, data, form=form)
return TemplateResponse(request, "book/edit/edit_book.html", data)
# we have to call this twice because it requires form.cleaned_data
# which only exists after we validate the form
ensure_transient_values_persist(request, data, form=form)
data = add_authors(request, data)
# check if this is an edition of an existing work
@ -139,9 +142,15 @@ class CreateBook(View):
return redirect(f"/book/{book.id}")
def ensure_transient_values_persist(request, data):
def ensure_transient_values_persist(request, data, **kwargs):
"""ensure that values of transient form fields persist when re-rendering the form"""
data["cover_url"] = request.POST.get("cover-url")
if kwargs and kwargs.get("form"):
data["book"] = data.get("book") or {}
data["book"]["subjects"] = kwargs["form"].cleaned_data["subjects"]
data["add_author"] = request.POST.getlist("add_author")
elif kwargs and kwargs.get("add_author") is True:
data["add_author"] = request.POST.getlist("add_author")
def add_authors(request, data):