Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Uses custom date select widget for publication dates #2044

Merged
merged 2 commits into from
Mar 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 4 additions & 11 deletions bookwyrm/forms/books.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from bookwyrm import models
from bookwyrm.models.fields import ClearableFileInputWithWarning
from .custom_form import CustomForm
from .widgets import ArrayWidget, SelectDateWidget, Select


# pylint: disable=missing-class-docstring
Expand All @@ -14,14 +15,6 @@ class Meta:
help_texts = {f: None for f in fields}


class ArrayWidget(forms.widgets.TextInput):
# pylint: disable=unused-argument
# pylint: disable=no-self-use
def value_from_datadict(self, data, files, name):
"""get all values for this name"""
return [i for i in data.getlist(name) if i]


class EditionForm(CustomForm):
class Meta:
model = models.Edition
Expand Down Expand Up @@ -56,16 +49,16 @@ class Meta:
"publishers": forms.TextInput(
attrs={"aria-describedby": "desc_publishers_help desc_publishers"}
),
"first_published_date": forms.SelectDateWidget(
"first_published_date": SelectDateWidget(
attrs={"aria-describedby": "desc_first_published_date"}
),
"published_date": forms.SelectDateWidget(
"published_date": SelectDateWidget(
attrs={"aria-describedby": "desc_published_date"}
),
"cover": ClearableFileInputWithWarning(
attrs={"aria-describedby": "desc_cover"}
),
"physical_format": forms.Select(
"physical_format": Select(
attrs={"aria-describedby": "desc_physical_format"}
),
"physical_format_detail": forms.TextInput(
Expand Down
70 changes: 70 additions & 0 deletions bookwyrm/forms/widgets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
""" using django model forms """
from django import forms


class ArrayWidget(forms.widgets.TextInput):
"""Inputs for postgres array fields"""

# pylint: disable=unused-argument
# pylint: disable=no-self-use
def value_from_datadict(self, data, files, name):
"""get all values for this name"""
return [i for i in data.getlist(name) if i]


class Select(forms.Select):
"""custom template for select widget"""

template_name = "widgets/select.html"


class SelectDateWidget(forms.SelectDateWidget):
"""
A widget that splits date input into two <select> boxes and a numerical year.
"""

template_name = "widgets/addon_multiwidget.html"
select_widget = Select

def get_context(self, name, value, attrs):
"""sets individual widgets"""
context = super().get_context(name, value, attrs)
date_context = {}
year_name = self.year_field % name
date_context["year"] = forms.NumberInput().get_context(
name=year_name,
value=context["widget"]["value"]["year"],
attrs={
**context["widget"]["attrs"],
"id": f"id_{year_name}",
"class": "input",
},
)
month_choices = list(self.months.items())
if not self.is_required:
month_choices.insert(0, self.month_none_value)
month_name = self.month_field % name
date_context["month"] = self.select_widget(
attrs, choices=month_choices
).get_context(
name=month_name,
value=context["widget"]["value"]["month"],
attrs={**context["widget"]["attrs"], "id": f"id_{month_name}"},
)
day_choices = [(i, i) for i in range(1, 32)]
if not self.is_required:
day_choices.insert(0, self.day_none_value)
day_name = self.day_field % name
date_context["day"] = self.select_widget(
attrs,
choices=day_choices,
).get_context(
name=day_name,
value=context["widget"]["value"]["day"],
attrs={**context["widget"]["attrs"], "id": f"id_{day_name}"},
)
subwidgets = []
for field in self._parse_date_fmt():
subwidgets.append(date_context[field]["widget"])
context["widget"]["subwidgets"] = subwidgets
return context
9 changes: 3 additions & 6 deletions bookwyrm/templates/book/edit/edit_book_form.html
Original file line number Diff line number Diff line change
Expand Up @@ -155,16 +155,15 @@ <h2 class="title is-4">
<label class="label" for="id_first_published_date">
{% trans "First published date:" %}
</label>
<input type="date" name="first_published_date" class="input" id="id_first_published_date"{% if form.first_published_date.value %} value="{{ form.first_published_date.value|date:'Y-m-d' }}"{% endif %} aria-describedby="desc_first_published_date">

{{ form.first_published_date }}
{% include 'snippets/form_errors.html' with errors_list=form.first_published_date.errors id="desc_first_published_date" %}
</div>

<div class="field">
<label class="label" for="id_published_date">
{% trans "Published date:" %}
</label>
<input type="date" name="published_date" class="input" id="id_published_date"{% if form.published_date.value %} value="{{ form.published_date.value|date:'Y-m-d'}}"{% endif %} aria-describedby="desc_published_date">
{{ form.published_date }}

{% include 'snippets/form_errors.html' with errors_list=form.published_date.errors id="desc_published_date" %}
</div>
Expand Down Expand Up @@ -259,9 +258,7 @@ <h2 class="title is-4">
<label class="label" for="id_physical_format">
{% trans "Format:" %}
</label>
<div class="select">
{{ form.physical_format }}
</div>
{{ form.physical_format }}

{% include 'snippets/form_errors.html' with errors_list=form.physical_format.errors id="desc_physical_format" %}
</div>
Expand Down
9 changes: 9 additions & 0 deletions bookwyrm/templates/widgets/addon_multiwidget.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{% spaceless %}
<div class="field has-addons">
{% for widget in widget.subwidgets %}
<div class="control{% if forloop.last %} is-expanded{% endif %}">
{% include widget.template_name %}
</div>
{% endfor %}
</div>
{% endspaceless %}
10 changes: 10 additions & 0 deletions bookwyrm/templates/widgets/select.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<div class="select">
<select
name="{{ widget.name }}"
{% include "django/forms/widgets/attrs.html" %}
>{% for group_name, group_choices, group_index in widget.optgroups %}{% if group_name %}
<optgroup label="{{ group_name }}">{% endif %}{% for option in group_choices %}
{% include option.template_name with widget=option %}{% endfor %}{% if group_name %}
</optgroup>{% endif %}{% endfor %}
</select>
</div>
19 changes: 0 additions & 19 deletions bookwyrm/views/books/edit_book.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
""" the good stuff! the books! """
from re import sub, findall
from dateutil.parser import parse as dateparse
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.postgres.search import SearchRank, SearchVector
from django.db import transaction
from django.http import HttpResponseBadRequest
from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
from django.utils.datastructures import MultiValueDictKeyError
from django.utils.decorators import method_decorator
from django.views.decorators.http import require_POST
from django.views import View
Expand Down Expand Up @@ -52,7 +50,6 @@ def post(self, request, book_id):

# either of the above cases requires additional confirmation
if data.get("add_author"):
data = copy_form(data)
return TemplateResponse(request, "book/edit/edit_book.html", data)

remove_authors = request.POST.getlist("remove_authors")
Expand Down Expand Up @@ -118,7 +115,6 @@ def post(self, request):

# go to confirm mode
if not parent_work_id or data.get("add_author"):
data = copy_form(data)
return TemplateResponse(request, "book/edit/edit_book.html", data)

with transaction.atomic():
Expand All @@ -139,21 +135,6 @@ def post(self, request):
return redirect(f"/book/{book.id}")


def copy_form(data):
"""helper to re-create the date fields in the form"""
formcopy = data["form"].data.copy()
try:
formcopy["first_published_date"] = dateparse(formcopy["first_published_date"])
except (MultiValueDictKeyError, ValueError):
pass
try:
formcopy["published_date"] = dateparse(formcopy["published_date"])
except (MultiValueDictKeyError, ValueError):
pass
data["form"].data = formcopy
return data


def add_authors(request, data):
"""helper for adding authors"""
add_author = [author for author in request.POST.getlist("add_author") if author]
Expand Down