feat: add metadata form fixture and enhance field serialization for A… - #27
Closed
metaforx wants to merge 2 commits into
Closed
feat: add metadata form fixture and enhance field serialization for A…#27metaforx wants to merge 2 commits into
metaforx wants to merge 2 commits into
Conversation
Contributor
Reviewer's GuideAdds a metadata form test fixture and extends the form-fields API to include placeholder and serialized initial values in responses, ensuring JSON-safe handling of initial values. Sequence diagram for extended form-fields API responsesequenceDiagram
actor Client
participant APIView as FormFieldsAPIView
participant ViewFn as get_form_fields
participant Serializer as _serialize_initial
participant DjangoField as DjangoFormField
participant Response as DRFResponse
Client->>APIView: GET /api/form-fields/{slug}
APIView->>ViewFn: get_form_fields(request, slug)
ViewFn->>DjangoField: iterate form.fields.items()
DjangoField-->>ViewFn: field_name, field
ViewFn->>DjangoField: read widget.attrs
DjangoField-->>ViewFn: placeholder
ViewFn->>DjangoField: read initial
DjangoField-->>ViewFn: initial_value
ViewFn->>Serializer: _serialize_initial(initial_value)
Serializer-->>ViewFn: json_safe_initial
ViewFn-->>APIView: list of field_info
APIView->>Response: Response(field_info_list)
Response-->>Client: 200 OK JSON (includes placeholder, initial)
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Contributor
There was a problem hiding this comment.
Hey - I've found 2 issues, and left some high level feedback:
- In
_serialize_initial, you currently returnNonefor any callable initial; if some fields use callables to provide dynamic defaults, consider evaluating the callable or at least documenting why these are intentionally omitted from the API. - The
_serialize_initialhelper relies onhasattr(value, "isoformat"); you may want to narrow this to explicitdatetime/datetypes (or similar) to avoid unexpected behavior for other objects that happen to expose anisoformatmethod.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- In `_serialize_initial`, you currently return `None` for any callable initial; if some fields use callables to provide dynamic defaults, consider evaluating the callable or at least documenting why these are intentionally omitted from the API.
- The `_serialize_initial` helper relies on `hasattr(value, "isoformat")`; you may want to narrow this to explicit `datetime`/`date` types (or similar) to avoid unexpected behavior for other objects that happen to expose an `isoformat` method.
## Individual Comments
### Comment 1
<location path="src/unfold_fobi/api/views.py" line_range="22-26" />
<code_context>
from rest_framework.response import Response
+def _serialize_initial(value):
+ """Return a JSON-friendly initial value for API responses."""
+ if callable(value):
+ return None
+ if value is None:
+ return None
+ if hasattr(value, "isoformat"):
+ try:
+ return value.isoformat()
+ except Exception:
+ return value
+ return value
</code_context>
<issue_to_address>
**suggestion (bug_risk):** Fallback branch may return non-JSON-serializable values despite the function's contract.
Because `isoformat()` failures fall through to returning the original `value`, this can still yield non-JSON-serializable objects. To preserve the contract and avoid runtime serialization errors, the `except` branch should convert to a safe type (e.g. `str(value)`) or return `None`/omit the field on failure.
```suggestion
if hasattr(value, "isoformat"):
try:
return value.isoformat()
except Exception:
# Fall back to a string representation to keep the return JSON-serializable.
return str(value)
```
</issue_to_address>
### Comment 2
<location path="src/unfold_fobi/api/views.py" line_range="176" />
<code_context>
}
for field_name, field in fields.items():
+ widget_attrs = getattr(getattr(field, "widget", None), "attrs", {})
field_info = {
"name": field_name,
</code_context>
<issue_to_address>
**issue:** Potential `AttributeError` if `widget.attrs` exists but is `None` rather than a dict.
If a custom widget sets `attrs = None`, this expression will return `None` and `widget_attrs.get("placeholder")` will raise `AttributeError`. Consider normalizing to a dict, e.g.:
```python
widget = getattr(field, "widget", None)
widget_attrs = getattr(widget, "attrs", {}) or {}
```
or use a type check after `getattr` to ensure `widget_attrs` is a dict before use.
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
| } | ||
|
|
||
| for field_name, field in fields.items(): | ||
| widget_attrs = getattr(getattr(field, "widget", None), "attrs", {}) |
Contributor
There was a problem hiding this comment.
issue: Potential AttributeError if widget.attrs exists but is None rather than a dict.
If a custom widget sets attrs = None, this expression will return None and widget_attrs.get("placeholder") will raise AttributeError. Consider normalizing to a dict, e.g.:
widget = getattr(field, "widget", None)
widget_attrs = getattr(widget, "attrs", {}) or {}or use a type check after getattr to ensure widget_attrs is a dict before use.
…le datetime objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
…PI responses
Summary by Sourcery
Expose additional field metadata in form fields API responses and add coverage for placeholder and initial values.
New Features:
Enhancements:
Tests: