Skip to content

Commit

Permalink
DictionaryField 🤑
Browse files Browse the repository at this point in the history
  • Loading branch information
Sibyx committed Nov 13, 2019
1 parent 123c59c commit a360b84
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 3 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 0.4.0 : 13.11.2019

- **Feature**: Introduced `DictionaryField`

## 0.3.0 : 11.11.2019

- **Feature**: Propagate `kwargs` from `Form.is_valid()` to `Form.validate()` and `Form.validate_{key}()` methods.
Expand Down
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,10 @@ python setup.py install
"duration": "4:48"
}
],
"created_at": "2019-10-21T18:57:03+00:00"
"metadata": {
"created_at": "2019-10-21T18:57:03+00:00",
"updated_at": "2019-10-21T18:57:03+00:00"
}
}
```

Expand Down Expand Up @@ -97,7 +100,7 @@ class AlbumForm(Form):
year = fields.IntegerField()
artist = fields.FormField(form=ArtistForm)
songs = fields.FormFieldList(form=SongForm)
created_at = fields.DateField()
metadata = fields.DictionaryField(fields.DateTimeField())

def validate_year(self, value):
if value == "1992":
Expand Down
2 changes: 1 addition & 1 deletion django_request_formatter/__version__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '0.3.0'
__version__ = '0.4.0'
32 changes: 32 additions & 0 deletions django_request_formatter/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,7 @@ def validate(self, value):
if isinstance(self.field, Field):
self.field.validate(item)
else:
# TODO: toto nemoze byt RuntimeError
raise RuntimeError(f"Invalid field_type {type(self.field)} in FieldList")


Expand Down Expand Up @@ -408,3 +409,34 @@ def validate(self, value):
self.enum(value)
except ValueError:
raise ValidationError(f"Invalid enum value {value} passed to {type(self.enum)}")


class DictionaryField(Field):
def __init__(self, value, **kwargs):
if not isinstance(value, Field):
raise RuntimeError("Invalid Field type passed into DictionaryField!")
self._value = value
super().__init__(**kwargs)

def to_python(self, value) -> dict:
result = {}

for key, item in value.items():
result[key] = self._value.to_python(item)

return result

def validate(self, value):
if not isinstance(value, dict):
raise ValidationError(f"Invalid value passed to DictionaryField (got {type(value)}, expected dict)")

errors = {}

for key, item in value.items():
try:
self._value.validate(value)
except ValidationError as e:
errors[key] = e

if errors:
raise ValidationError(errors)

0 comments on commit a360b84

Please sign in to comment.