Skip to content

Commit

Permalink
Merge pull request #2827 from hughrun/2571
Browse files Browse the repository at this point in the history
Retain subjects and authors when new book form fails validation
  • Loading branch information
mouse-reeve authored May 30, 2023
2 parents 9056a5d + 5c9b962 commit ca3054f
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions bookwyrm/views/books/edit_book.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ def post(self, request, book_id):
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)
Expand Down Expand Up @@ -102,11 +103,13 @@ def post(self, request):
"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
Expand Down Expand Up @@ -139,9 +142,15 @@ def post(self, request):
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):
Expand Down

0 comments on commit ca3054f

Please sign in to comment.