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

2712: Add class is-danger to fields with errors #2845

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
41 changes: 41 additions & 0 deletions bookwyrm/forms/custom_form.py
@@ -1,5 +1,6 @@
""" Overrides django's default form class """
from collections import defaultdict
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from django.forms.widgets import Textarea

Expand Down Expand Up @@ -34,3 +35,43 @@ def save(self, request, *args, **kwargs):
"""Save and check perms"""
self.instance.raise_not_editable(request.user)
return super().save(*args, **kwargs)

# def clean(self):
# self.cleaned_data = super().clean()

# print("Clean")
# print(self.errors)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is empty at this position.

Which surprises me after reading documentation...


# for name, field in self.fields.items():
# if self.has_error(field):
# print(field.widget.__dir__())
# self.add_to_attributes(field, "class", "is-danger")

# return self.cleaned_data

def add_error(self, field, error):
super().add_error(field, error)

# TODO this (finding the field) is much too complicated; probably this is not the right location?
# it is however more or less what super().add_error does...
if (field is None):
if isinstance(error, dict):
for field_name, messages in error.items():
if field_name in self.fields:
self.add_to_attributes(self.fields[field_name], "class", "is-danger")
elif isinstance(error, ValidationError):
if hasattr(error, 'error_dict'):
error = error.error_dict
for field_name, error_list in error.items():
if field_name in self.fields:
self.add_to_attributes(self.fields[field_name], "class", "is-danger")
else:
self.add_to_attributes(field, "class", "is-danger")

# TODO this method looks much too complicated for a simple "field.add_class(class)"?
def add_to_attributes(self, field, attr_name, value):
current_attributes = field.widget.attrs
current_classes = set(current_attributes.get(attr_name, "").split())
current_classes.add(value)

current_attributes[attr_name] = " ".join(current_classes)