Description
Description:
In views.py
, inside the edit
view, we’re looping over an HStoreField
like so:
for k, v in m.tags.items():
tags.append(f"{k}={v}")
Here, m.tags
is an HStoreField
.
This works as expected when the view is accessed through a browser: type(m.tags)
is dict
.
However, during test execution, type(m.tags)
is unexpectedly str
, leading to a runtime error when a GET request is made to edit/<model_id>/<revision>
:
AttributeError: 'str' object has no attribute 'items'
Suspected Cause:
The HStoreField
stores data as a string internally and relies on its to_python()
method to convert that into a dict
upon access. My assumption is that during test execution, this serialization doesn't happen reliably by the Django's test framework.
A similar behavior has been reported in Django Ticket #31221. The ticket doesn't suggest that the issue has yet been resolved in Django codebase.
Proposed Workaround:
As per my understanding i am considering an explicit type check to handle this safely:
if isinstance(m.tags, str):
tags_iterable = json.loads(m.tags).items()
elif isinstance(m.tags, dict):
tags_iterable = m.tags.items()
else:
raise TypeError("Unexpected type for m.tags")
for k, v in tags_iterable:
tags.append(f"{k}={v}")
Would appreciate thoughts and guidance on the best long-term solution here.