From 742231f45050ec1589379370c24c37fad3bb86ef Mon Sep 17 00:00:00 2001 From: Radoslav Georgiev Date: Sat, 16 Jul 2016 17:50:39 +0300 Subject: [PATCH] Add example for message property for custom permissions - If you want to have more control over the error message, you can define a `@property` for `message` and make DB calls, if needed. --- docs/api-guide/permissions.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 402875cd5..d2ed660e4 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -206,6 +206,22 @@ Custom permissions will raise a `PermissionDenied` exception if the test fails. def has_permission(self, request, view): ... + +If you want to have more control over the error message, for example, format with data, fetched from the database, you can define a `message` property in the permission class: + + from rest_framework import permissions + + class CustomerAccessPermission(permissions.BasePermission): + @property + def message(self): + product = SomeProductModel.objects.get(...) + return 'Adding customers for product {} not allowed.'.format(product.name) + + def has_permission(self, request, view): + ... + + + ## Examples The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted.