prompt: 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 import logging
  3 
  4 from django import forms
  5 from django.http import QueryDict
  6 from django.utils.datastructures import MultiValueDict
  7 
  8 logger = logging.getLogger("amy")
  9 
  10 
  11 class CustomKeysWidget(forms.TextInput):
  12     template_name = "widgets/custom_keys_widget.html"
  13 
  14     def __init__(self, *args, **kwargs):
  15         self.subwidget_form = kwargs.pop("subwidget_form", forms.TextInput)
  16         super().__init__(*args, **kwargs)
  17 
  18     def apply_labels(self, labels: list[str]) -> None:
  19         self.labels = labels[:]
  20 
  21     def get_context(self, name: str, value: str, attrs: dict):
  22         value_deserialized = json.loads(value)
  23         try:
  24             value_deserialized_dict = dict(value_deserialized)
  25         except (ValueError, TypeError) as e:
  26             logger.debug(
  27                 f"Failed to load custom key values {value_deserialized} to dict: {e}."
  28             )
  29             logger.debug("Proceeding without custom key values...")
  30             value_deserialized_dict = {}
  31         default_values = dict([(label, "") for label in self.labels])
  32         context_value = default_values | value_deserialized_dict
  33 
  34         context = super().get_context(name, context_value, attrs)
  35         final_attrs = context["widget"]["attrs"]
  36         id_ = context["widget"]["attrs"].get("id")
  37 
  38         subwidgets = []
  39         for index, (label, value) in enumerate(context_value.items()):
  40             widget_attrs = final_attrs.copy()
  41             if id_:
  42                 widget_attrs["id"] = "{id_}_{index}".format(id_=id_, index=index)
  43 
  44             widget = self.subwidget_form()
  45             subwidget_context = widget.get_context(name, value, widget_attrs)["widget"]
  46             subwidgets.append(subwidget_context | {"label": label})
  47 
  48         context["widget"]["subwidgets"] = subwidgets
  49         return context
  50 
  51     def value_from_datadict(
  52         self, data: QueryDict, files: MultiValueDict, name: str
  53     ) -> list[tuple[str, str]]:
  54         """Prepare structure stored in database. The structure is tied to
  55         `CommunityRole.custom_keys` expected format:
  56             [
  57                 (label1, value1),
  58                 (label2, value2),
  59                 ...
  60             ]
  61         """
  62         try:
  63             values = data.getlist(name)
  64         except AttributeError:
  65             values = data.get(name, [])
  66         return list(zip(self.labels, values))
  67 
  68     def value_omitted_from_data(
  69         self, data: QueryDict, files: MultiValueDict, name: str
  70     ) -> bool:
  71         return False
  72 
  73 
  74 class CustomKeysJSONField(forms.JSONField):
  75     def __init__(self, **kwargs):
  76         kwargs.setdefault("widget", CustomKeysWidget)
  77         super().__init__(**kwargs)
  78 
  79     def apply_labels(self, labels: list[str]) -> None:
  80         self.labels = labels[:]
  81         self.widget.apply_labels(self.labels)
  82
  ```
  --- 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()
  
  ```
  
golden_diff: diff --git a/amy/communityroles/fields.py b/amy/communityroles/fields.py
  --- a/amy/communityroles/fields.py
  +++ b/amy/communityroles/fields.py
  @@ -63,7 +63,7 @@
               values = data.getlist(name)
           except AttributeError:
               values = data.get(name, [])
  -        return list(zip(self.labels, values))
  +        return json.dumps(list(zip(self.labels, values)))
   
       def value_omitted_from_data(
           self, data: QueryDict, files: MultiValueDict, name: str
  
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@@ -63,7 +63,7 @@\n             values = data.getlist(name)\n         except AttributeError:\n             values = data.get(name, [])\n-        return list(zip(self.labels, values))\n+        return json.dumps(list(zip(self.labels, values)))\n \n     def value_omitted_from_data(\n         self, data: QueryDict, files: MultiValueDict, name: str\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\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"}], "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 json.dumps(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"}]}