We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN 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

```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `amy/communityroles/fields.py`
Content:
```
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 FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

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

{"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"}], "after_files": [{"content": "import json\nimport logging\n\nfrom django import forms\nfrom django.http import QueryDict\nfrom django.utils.datastructures import MultiValueDict\n\nlogger = logging.getLogger(\"amy\")\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        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\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"}]}