Returning pure Django form errors in JSON

前端 未结 6 2020
青春惊慌失措
青春惊慌失措 2020-12-12 16:50

I have a Django form which I\'m validating in a normal Django view. I\'m trying to figure out how to extract the pure errors (without the HTML formatting). Below is the code

6条回答
  •  萌比男神i
    2020-12-12 17:35

    json.dumps can't serialize django's proxy function (like lazy translations).

    As documented you should create a new Encoder class:

    import json
    from django.utils.functional import Promise
    from django.utils.encoding import force_text
    from django.core.serializers.json import DjangoJSONEncoder
    
    class LazyEncoder(DjangoJSONEncoder):
        def default(self, obj):
            if isinstance(obj, Promise):
                return force_text(obj)
            return super(LazyEncoder, self).default(obj)
    

    Use the new Encoder like this:

    json.dumps(s, cls=LazyEncoder)
    

    That's all :)

提交回复
热议问题