seebass / drf-enum-field Goto Github PK
View Code? Open in Web Editor NEWEnumField support for Django REST Framework 3
License: MIT License
EnumField support for Django REST Framework 3
License: MIT License
Currently you have
def to_representation(self, value): if not value: return None return value.name
If I understand correctly this results in the ignorance of the actual value of the enums.
I think it should simply return value.
This was reported by @Tim-Erwin over at encode/django-rest-framework#3247
When I make a POST on a viewset with a model that has an EnumField and I use an invalid value for that field, I get the error message
'tuple' object has no attribute 'format'
The reasons seems to be in fields.py:
default_error_messages = { 'invalid': ("No matching enum type.",) }It should be not be a tuple but a simple or translated string.
The issue occurs because of this line.
If value for enum field is invalid the error message 'No matching enum type.'
is given. As a API User I don't care about the type. Better should be something like '%s is not a valid choice.' % value
.
Because the serializer checks for ChoiceFields, it misses EnumIntegerFields.
Changing https://github.com/seebass/drf-enum-field/blob/master/drf_enum_field/serializers.py#L10 can resolve this.
From if field_class == ChoiceField and isinstance(model_field, EnumField):
To if isinstance(model_field, EnumFieldMixin):
Resolves the issue for reading.
For writing, the value in the data is returned as a text_type.
The simplest way to fix this is to wrap choice.value == data
into text_type(choice.value) == data
It would be neater to check if the value is an int, then attempt to parse the data as an int, but it is not necessary.
Please let me know if you are willing to accept pull requests on this.
Using drf-enum-fields with latest Django (3.0) results in warnings like
/usr/local/lib/python3.6/site-packages/drf_enum_field/fields.py:7
/usr/local/lib/python3.6/site-packages/drf_enum_field/fields.py:7: RemovedInDjango40Warning: django.utils.translation.ugettext_lazy() is deprecated in favor of django.utils.translation.gettext_lazy().
'invalid': _("No matching enum type.")
EnumFieldSerializerMixin always serializes lowercase value as uppercase. This breaks import for serialized data.
DEFAULT = 'default' is always serialized as DEFAULT. This breaks import on serialized data.
Your EnumField
doesn't take positional arguments yet the example:
type = EnumField(Type)
shows it does.
Hello,
I'm new to python programming, but I have to serialize django-enum-fields.
I was looking at your module. But when I try to use it I got an " attribute error at MYURL choices ..."
I'm using the same code as you in you test project, except for the urls.py where the code is like :
# django core
from django.urls import path
from .views import LangList, LemmeList, StatList
app_name = 'search'
urlpatterns = [
path('', LangList.as_view()),
]
my views.py :
class LangList(views.APIView):
def get(self, request, lang=None, resources=None):
queryset = Resource.objects.all()
serializer_class = ResourcesSerializer(queryset, many=True)
return response.Response(serializer_class.data, status=status.HTTP_200_OK)
and my models.py :
class Type(enum.Enum):
DEFAULT = 'DEFAULT'
NON_DEFAULT = 'NON_DEFAULT'
class Resource(models.Model):
type = EnumField(Type)
@classmethod
def from_file(cls, filepath, *args, **kwargs):
raise NotImplementedError()
I don't understand what's wrong in my code and how I can solve my problem.
Can I ask you to help me using you module and finding a solution?
sincerly yours.
Now supported only enumfields enums, when trying to use PEP enums i get it:
File "/home/joe/repo/disputes/back/.venv/lib/python3.4/site-packages/drf_enum_field/fields.py" in __init__
12. super(EnumField, self).__init__(self.enum_type.choices(), **kwargs)
File "/usr/lib/python3.4/enum.py" in __getattr__
255. raise AttributeError(name) from None
Exception Type: AttributeError at /api/v1/arguments/
Exception Value: choices
I use Python 3 and standart enum
module.
It defines a tuple:
default_error_messages = {
'invalid': ("No matching enum type.",)
}
Should be a string instead (without the comma):
default_error_messages = {
'invalid': ("No matching enum type.")
}
Otherwise we will get "AttributeError: 'tuple' object has no attribute 'format'" when calling self.fail('invalid') .
Imagine you have an Enum:
class Color(Enum):
RED = 'red'
GREEN = 'green'
And a model with property that returns Color instance:
class Paint(models.Model):
@property
def color(self):
return Color.RED
Adding color
to serializer fields
list would cause TypeError: Object of type 'Color' is not JSON serializable.
Any ideas how to implement something like this?
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.