Forms ValidationError and error code

后端 未结 2 862
我在风中等你
我在风中等你 2021-01-03 22:09

In Django documentation https://docs.djangoproject.com/en/dev/ref/forms/validation/#raising-validationerror said that it is good practice to prodive error code while raising

相关标签:
2条回答
  • 2021-01-03 22:16

    In Django 1.7, you can now access the original error data from the form. You can call the as_data() method on an ErrorList or ErrorDict. For example: my_form.errors.as_data(). This basically gives you the original ValidationError object instead of the message itself. From this you can access the .code property, eg: my_form.errors["__all__"].as_data()[0].code.

    You can also serialize form errors, great for APIs:

    >>> print(form.errors.as_json())
    {"__all__": [
        {"message": "Your account has not been activated.", "code": "inactive"}
    ]}
    
    0 讨论(0)
  • 2021-01-03 22:33

    Take a look at ValidationError definition in django src, it's used as a convenient way to pass additional identifier (similar to e.errno in standard python exception), you can use it like this:

    try:
        ...
        raise ValidationError(u'Oops', code=0x800)
        ...
    
    except ValidationError as e:
        print "Error code: ", e.code
    
    0 讨论(0)
提交回复
热议问题