Coder Social home page Coder Social logo

drf-enum-field's People

Contributors

aram2726 avatar archelyst avatar belugame avatar jeroenoldenburger avatar seebass avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

drf-enum-field's Issues

EnumField to_representation

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.

Invalid default_error_message in EnumField

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.

Serializer error message

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.

EnumFieldSerializerMixin Fails for EnumIntegerFields

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.

Warnings when using Django 3.0 or later

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.")

Faulty example

Your EnumField doesn't take positional arguments yet the example:

type = EnumField(Type)

shows it does.

AttributeError: choices

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.

PEP-435 enums support

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.

EnumField default_error_messages looks wrong

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') .

Is it possible to serialize properties?

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?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.