prompt: You will be provided with a partial code base and an issue statement explaining a problem to resolve.
  <issue>
  Server Error when editing community roles
  Reported by @ErinBecker at `/workshops/person/<id>/edit/#communityroles` and `/communityroles/role/<another id>/edit/` in production.
  
  Reproduced on test AMY:
  ```
  TypeError at /communityroles/role/25/edit/
  the JSON object must be str, bytes or bytearray, not list
  Error during template rendering
  In template /webapps/test-amy.carpentries.org/repo/amy/templates/bootstrap4/field.html, error at line 39
  
  {% crispy_field field %}
  ```
  
  Also encountered locally when creating a community role and immediately editing it:
  ```
  Exception Value: | 'NoneType' object is not iterable
  /home/eli/amy/amy/communityroles/fields.py, line 20, in get_context
  
  ```
  
  </issue>
  <code>
  [start of amy/communityroles/fields.py]
  1 import json
  2 
  3 from django import forms
  4 from django.http import QueryDict
  5 from django.utils.datastructures import MultiValueDict
  6 
  7 
  8 class CustomKeysWidget(forms.TextInput):
  9     template_name = "widgets/custom_keys_widget.html"
  10 
  11     def __init__(self, *args, **kwargs):
  12         self.subwidget_form = kwargs.pop("subwidget_form", forms.TextInput)
  13         super().__init__(*args, **kwargs)
  14 
  15     def apply_labels(self, labels: list[str]) -> None:
  16         self.labels = labels[:]
  17 
  18     def get_context(self, name: str, value: str, attrs: dict):
  19         value_deserialized = json.loads(value)
  20         value_deserialized_dict = dict(value_deserialized)
  21         default_values = dict([(label, "") for label in self.labels])
  22         context_value = default_values | value_deserialized_dict
  23 
  24         context = super().get_context(name, context_value, attrs)
  25         final_attrs = context["widget"]["attrs"]
  26         id_ = context["widget"]["attrs"].get("id")
  27 
  28         subwidgets = []
  29         for index, (label, value) in enumerate(context_value.items()):
  30             widget_attrs = final_attrs.copy()
  31             if id_:
  32                 widget_attrs["id"] = "{id_}_{index}".format(id_=id_, index=index)
  33 
  34             widget = self.subwidget_form()
  35             subwidget_context = widget.get_context(name, value, widget_attrs)["widget"]
  36             subwidgets.append(subwidget_context | {"label": label})
  37 
  38         context["widget"]["subwidgets"] = subwidgets
  39         return context
  40 
  41     def value_from_datadict(
  42         self, data: QueryDict, files: MultiValueDict, name: str
  43     ) -> list[tuple[str, str]]:
  44         """Prepare structure stored in database. The structure is tied to
  45         `CommunityRole.custom_keys` expected format:
  46             [
  47                 (label1, value1),
  48                 (label2, value2),
  49                 ...
  50             ]
  51         """
  52         try:
  53             values = data.getlist(name)
  54         except AttributeError:
  55             values = data.get(name, [])
  56         return list(zip(self.labels, values))
  57 
  58     def value_omitted_from_data(
  59         self, data: QueryDict, files: MultiValueDict, name: str
  60     ) -> bool:
  61         return False
  62 
  63 
  64 class CustomKeysJSONField(forms.JSONField):
  65     def __init__(self, **kwargs):
  66         kwargs.setdefault("widget", CustomKeysWidget)
  67         super().__init__(**kwargs)
  68 
  69     def apply_labels(self, labels: list[str]) -> None:
  70         self.labels = labels[:]
  71         self.widget.apply_labels(self.labels)
  72
  [end of amy/communityroles/fields.py]
  </code>
  
  I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format.
  <patch>
  diff --git a/file.py b/file.py
  --- a/file.py
  +++ b/file.py
  @@ -1,27 +1,35 @@
   def euclidean(a, b):
  -    while b:
  -        a, b = b, a % b
  -    return a
  +    if b == 0:
  +        return a
  +    return euclidean(b, a % b)
   
   
   def bresenham(x0, y0, x1, y1):
       points = []
       dx = abs(x1 - x0)
       dy = abs(y1 - y0)
  -    sx = 1 if x0 < x1 else -1
  -    sy = 1 if y0 < y1 else -1
  -    err = dx - dy
  +    x, y = x0, y0
  +    sx = -1 if x0 > x1 else 1
  +    sy = -1 if y0 > y1 else 1
   
  -    while True:
  -        points.append((x0, y0))
  -        if x0 == x1 and y0 == y1:
  -            break
  -        e2 = 2 * err
  -        if e2 > -dy:
  -            err -= dy
  -            x0 += sx
  -        if e2 < dx:
  -            err += dx
  -            y0 += sy
  +    if dx > dy:
  +        err = dx / 2.0
  +        while x != x1:
  +            points.append((x, y))
  +            err -= dy
  +            if err < 0:
  +                y += sy
  +                err += dx
  +            x += sx
  +    else:
  +        err = dy / 2.0
  +        while y != y1:
  +            points.append((x, y))
  +            err -= dx
  +            if err < 0:
  +                x += sx
  +                err += dy
  +            y += sy
  +
  +    points.append((x, y))
       return points
  
  </patch>
golden_diff: diff --git a/amy/communityroles/fields.py b/amy/communityroles/fields.py
  --- a/amy/communityroles/fields.py
  +++ b/amy/communityroles/fields.py
  @@ -1,9 +1,12 @@
   import json
  +import logging
   
   from django import forms
   from django.http import QueryDict
   from django.utils.datastructures import MultiValueDict
   
  +logger = logging.getLogger("amy")
  +
   
   class CustomKeysWidget(forms.TextInput):
       template_name = "widgets/custom_keys_widget.html"
  @@ -17,7 +20,14 @@
   
       def get_context(self, name: str, value: str, attrs: dict):
           value_deserialized = json.loads(value)
  -        value_deserialized_dict = dict(value_deserialized)
  +        try:
  +            value_deserialized_dict = dict(value_deserialized)
  +        except (ValueError, TypeError) as e:
  +            logger.debug(
  +                f"Failed to load custom key values {value_deserialized} to dict: {e}."
  +            )
  +            logger.debug("Proceeding without custom key values...")
  +            value_deserialized_dict = {}
           default_values = dict([(label, "") for label in self.labels])
           context_value = default_values | value_deserialized_dict
  
verification_info: {"golden_diff": "diff --git a/amy/communityroles/fields.py b/amy/communityroles/fields.py\n--- a/amy/communityroles/fields.py\n+++ b/amy/communityroles/fields.py\n@@ -1,9 +1,12 @@\n import json\n+import logging\n \n from django import forms\n from django.http import QueryDict\n from django.utils.datastructures import MultiValueDict\n \n+logger = logging.getLogger(\"amy\")\n+\n \n class CustomKeysWidget(forms.TextInput):\n     template_name = \"widgets/custom_keys_widget.html\"\n@@ -17,7 +20,14 @@\n \n     def get_context(self, name: str, value: str, attrs: dict):\n         value_deserialized = json.loads(value)\n-        value_deserialized_dict = dict(value_deserialized)\n+        try:\n+            value_deserialized_dict = dict(value_deserialized)\n+        except (ValueError, TypeError) as e:\n+            logger.debug(\n+                f\"Failed to load custom key values {value_deserialized} to dict: {e}.\"\n+            )\n+            logger.debug(\"Proceeding without custom key values...\")\n+            value_deserialized_dict = {}\n         default_values = dict([(label, \"\") for label in self.labels])\n         context_value = default_values | value_deserialized_dict\n", "issue": "Server Error when editing community roles\nReported by @ErinBecker at `/workshops/person/<id>/edit/#communityroles` and `/communityroles/role/<another id>/edit/` in production.\r\n\r\nReproduced on test AMY:\r\n```\r\nTypeError at /communityroles/role/25/edit/\r\nthe JSON object must be str, bytes or bytearray, not list\r\nError during template rendering\r\nIn template /webapps/test-amy.carpentries.org/repo/amy/templates/bootstrap4/field.html, error at line 39\r\n\r\n{% crispy_field field %}\r\n```\r\n\r\nAlso encountered locally when creating a community role and immediately editing it:\r\n```\r\nException Value: | 'NoneType' object is not iterable\r\n/home/eli/amy/amy/communityroles/fields.py, line 20, in get_context\r\n\r\n```\n", "before_files": [{"content": "import json\n\nfrom django import forms\nfrom django.http import QueryDict\nfrom django.utils.datastructures import MultiValueDict\n\n\nclass CustomKeysWidget(forms.TextInput):\n    template_name = \"widgets/custom_keys_widget.html\"\n\n    def __init__(self, *args, **kwargs):\n        self.subwidget_form = kwargs.pop(\"subwidget_form\", forms.TextInput)\n        super().__init__(*args, **kwargs)\n\n    def apply_labels(self, labels: list[str]) -> None:\n        self.labels = labels[:]\n\n    def get_context(self, name: str, value: str, attrs: dict):\n        value_deserialized = json.loads(value)\n        value_deserialized_dict = dict(value_deserialized)\n        default_values = dict([(label, \"\") for label in self.labels])\n        context_value = default_values | value_deserialized_dict\n\n        context = super().get_context(name, context_value, attrs)\n        final_attrs = context[\"widget\"][\"attrs\"]\n        id_ = context[\"widget\"][\"attrs\"].get(\"id\")\n\n        subwidgets = []\n        for index, (label, value) in enumerate(context_value.items()):\n            widget_attrs = final_attrs.copy()\n            if id_:\n                widget_attrs[\"id\"] = \"{id_}_{index}\".format(id_=id_, index=index)\n\n            widget = self.subwidget_form()\n            subwidget_context = widget.get_context(name, value, widget_attrs)[\"widget\"]\n            subwidgets.append(subwidget_context | {\"label\": label})\n\n        context[\"widget\"][\"subwidgets\"] = subwidgets\n        return context\n\n    def value_from_datadict(\n        self, data: QueryDict, files: MultiValueDict, name: str\n    ) -> list[tuple[str, str]]:\n        \"\"\"Prepare structure stored in database. The structure is tied to\n        `CommunityRole.custom_keys` expected format:\n            [\n                (label1, value1),\n                (label2, value2),\n                ...\n            ]\n        \"\"\"\n        try:\n            values = data.getlist(name)\n        except AttributeError:\n            values = data.get(name, [])\n        return list(zip(self.labels, values))\n\n    def value_omitted_from_data(\n        self, data: QueryDict, files: MultiValueDict, name: str\n    ) -> bool:\n        return False\n\n\nclass CustomKeysJSONField(forms.JSONField):\n    def __init__(self, **kwargs):\n        kwargs.setdefault(\"widget\", CustomKeysWidget)\n        super().__init__(**kwargs)\n\n    def apply_labels(self, labels: list[str]) -> None:\n        self.labels = labels[:]\n        self.widget.apply_labels(self.labels)\n", "path": "amy/communityroles/fields.py"}]}