estebistec / drf-compound-fields Goto Github PK
View Code? Open in Web Editor NEWDjango-REST-framework serializer fields for compound types.
License: BSD 3-Clause "New" or "Revised" License
Django-REST-framework serializer fields for compound types.
License: BSD 3-Clause "New" or "Revised" License
As this is a new project, the following project loose ends need to be tied up to make this project as friendly and possible to consumers and contributors:
virtual/lib/python3.7/site-packages/drf_compound_fields/fields.py", line 10, in
from rest_framework.compat import six
ImportError: cannot import name 'six' from 'rest_framework.compat' (virtual/lib/python3.7/site-packages/rest_framework/compat.py)
I was following the documentation, trying to integrate this into a new django-rest-framework-based project, but I ran into trouble trying to use ListOrItemField(serializers.URLField())
. Namely, it never validates a list of URLs.
The documentation is correct when it comes to an item:
In [1]: from drf_compound_fields.fields import ListField
In [2]: from drf_compound_fields.fields import ListOrItemField
In [3]: from rest_framework import serializers
In [4]: class SkillsProfileSerializer(serializers.Serializer):
...: name = serializers.CharField()
...: skills = ListField(serializers.CharField(min_length=3))
...: social_links = ListOrItemField(serializers.URLField())
...:
In [5]: data = SkillsProfileSerializer({
...: 'name': 'John Smith',
...: 'skills': ['Python'],
...: 'social_links': 'http://chrp.com/johnsmith'
...: }).data
In [6]: sps = SkillsProfileSerializer(data=data)
In [7]: assert sps.is_valid(), sps.errors
But if you try to feed back in the serialized output of a list of URLs, it fails:
In [8]: data = SkillsProfileSerializer({
...: 'name': 'John Smith',
...: 'skills': ['Python'],
...: 'social_links': ['http://chrp.com/johnsmith', 'http://myface.com/johnsmith']
...: }).data
In [9]: data
Out[9]: {'name': u'John Smith', 'skills': [u'Python'], 'social_links': [u'http://chrp.com/johnsmith', u'http://myface.com/johnsmith']}
In [10]: sps = SkillsProfileSerializer(data=data)
In [11]: assert sps.is_valid(), sps.errors
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-10-6f75eb6cf39f> in <module>()
----> 1 assert sps.is_valid(), sps.errors
AssertionError: {'social_links': [u'Invalid value.']}
I haven't had time to implement a fix yet (trying to hit a deadline), but If you don't have time in the next couple days I should be able to loop back and figure out what's going wrong.
Note that that same data works fine for a ListField
:
In [12]: data
Out[12]: {'name': u'John Smith', 'skills': [u'Python'], 'social_links': [u'http://chrp.com/johnsmith', u'http://myface.com/johnsmith']}
In [13]: class SkillsProfileSerializer(serializers.Serializer):
...: name = serializers.CharField()
...: skills = ListField(serializers.CharField(min_length=3))
...: social_links = ListField(serializers.URLField())
...:
In [14]: sps = SkillsProfileSerializer(data=data)
In [15]: assert sps.is_valid(), sps.errors
I discovered this when working with ListOrItemField
and wanted to know if this usage-pattern is excluded by design or if this is a bug/feature.
(and what solution is preferred before I start working on a PR).
Example for my problem:
class SubSerializer(serializers.Serializer):
field_1 = serializers.IntegerField()
class MainSerializer(serializers.Serializer):
testfield = ListOrItemField(item_field=SubSerializer())
Is this field-type only designed to work with other fields? Or should we fix this?
Once we have a good release of this project, make a pull request to Django REST framework docs, on the fields page (and maybe a note on serializers near many=True), pointing to this project to get these extra field types.
Currently returning ValidationError instances in dictionaries that collect embedded errors. Looking at how embedded plural serializers (many=True
) behave, they appear to be just returning the messages. This package should to the same.
HT @mwarkentin
Following the instructions of how to setup a developer's environment and running the unit tests raises this error on python setup.py test
:
_____________________________________________________________________ ERROR collecting djangorestframework-2.3.14-py2.7.egg/rest_framework/tests/test_authentication.py ______________________________________________________________________
djangorestframework-2.3.14-py2.7.egg/rest_framework/tests/test_authentication.py:2: in
from django.contrib.auth.models import User
../../.virtualenvs/drf_compound_fields/lib/python2.7/site-packages/django/contrib/auth/init.py:6: in
from django.middleware.csrf import rotate_token
../../.virtualenvs/drf_compound_fields/lib/python2.7/site-packages/django/middleware/csrf.py:14: in
from django.utils.cache import patch_vary_headers
../../.virtualenvs/drf_compound_fields/lib/python2.7/site-packages/django/utils/cache.py:26: in
from django.core.cache import get_cache
../../.virtualenvs/drf_compound_fields/lib/python2.7/site-packages/django/core/cache/init.py:69: in
if DEFAULT_CACHE_ALIAS not in settings.CACHES:
../../.virtualenvs/drf_compound_fields/lib/python2.7/site-packages/django/conf/init.py:54: in getattr
self._setup(name)
../../.virtualenvs/drf_compound_fields/lib/python2.7/site-packages/django/conf/init.py:47: in _setup
% (desc, ENVIRONMENT_VARIABLE))
E ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
I'm not sure if it's some step missing in the docs or some problem on my virtualenv
A new version of Django is out, and drf-compund-fields is forcing Django to be downgraded when pip installing.
Perhaps the following might be a better option:
Django>=1.6"
The same issue affects the other dependencies listed in the requirements.txt
.
The isinstance(..., list)
check fails on queryset/manager values and so the repr
of the queryset/manager object is displayed as a single object instead of showing a list of objects.
The advice is probably to just use RelatedField
, but the reason for wanting to use ListOrItemField
is to allow older API clients which are expecting to set and get a single value to do so without making any changes.
There is no more WritableField in the drf, so it no longer works
It would be great to get validation on list lengths.
eg.
ListField(Field(...), max_length=10)
Hi, great work!
I have been using a customized DictField which will include part of dict if users specify included_keys = []. The motivation is that for a django's json field [https://bitbucket.org/schinckel/django-jsonfield/], I only want to return part of the data inside of that field. I am not sure if you are ok if I create a pull request for this. Thanks.
It would be very useful to be able to nest compound fields, such as a DictField inside of a ListField.
# [{"name": Joe, "username": joey, id: 12,}, {"name": "Sally", "username": "codehero", id: 2}]
my_field = ListField(DictField())
In my testing, this didn't seem to currently be possible. Is there a reason why it isn't supported?
We ran across a small bug with the ListField
when a string is passed in:
def from_native():
...
if self.item_field and data:
return [self.item_field.from_native(item_data) for item_data in data]
This was causing a List
of characters from the string to be passed into validate
, so if not isinstance(data, list):
wasn't actually being triggered. We moved the list check up into from_native
, and it seems to be working well.
If this is quick to do and simplifies test reading & writing, go for it.
Create a simple field type, building upon ListField, that allows values to be either lists or individual items of the embedded field-type.
E.g., ListOrItem(CharFIeld)
would validate and serialize either 'a'
or ['a', 'b', 'c']
.
Hi!
Here is a possible bug:
https://github.com/estebistec/drf-compound-fields/blob/master/drf_compound_fields/fields.py#L105
Shouldn't it be(?):
self.list_field = ListField(item_field, *args, **kwargs)
Otherwise validators may report required field error for some circumstances. Consider example:
myfield = ListOrItemField(IntegerField(), required=False, blank=True)
so, it woud result into:
[] -> Error myfield
is required
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.