django-adminactions icon indicating copy to clipboard operation
django-adminactions copied to clipboard

raising validation error when trying to merge instances with ArrayField

Open hanqyu opened this issue 5 years ago • 0 comments

The form validation raises error because the form render value of ArrayField into string not list.

ex.

['abc', 'bce'] -> "\[\'abc\',\'\bce\'\]"

I managed to solve this problem with detecting this value with regex and converting into list. Please refer to the snippet below, just in case.


def convert_stringfied_value_to_list(data: QueryDict, exclude_keys: list):
    def string_to_list(text):
        try:
            return json.loads(text.replace("'", '"'))
        except json.decoder.JSONDecodeError:
            return text

    def is_stringfied_list(value: str):
        if not isinstance(value, str):
            return False
        regex = r'^\[((([\'\w\[\]]\,?\s?))*)\]$'
        return re.match(regex, value)

    new_values = {key: string_to_list(value)
                  for key, value in data.items()
                  if is_stringified_list(value) and key not in exclude_keys}
    data._mutable = True
    data.update(new_values)
    data._mutable = False
    return data

# adminactions/merge.py:110
def validate(request, master, other):
    ...
    if merge_form.is_valid():
        form = MForm(request.POST, instance=master)
        form.data = convert_stringified_value_to_list(form.data, exclude_keys=form.declared_fields.keys())
    ...

hanqyu avatar Oct 07 '20 05:10 hanqyu