django-rest-framework-docs
django-rest-framework-docs copied to clipboard
setting the fields description if you are using function based views
How do I set the field descriptions in views.py on function based views?
This is my syntax: @api_view(['GET', 'POST']) def api_section(request): """ GET request gets the section and its details..... POST request, adds a new section """ if request.method == 'GET': sections = Section.objects.all() serializer = SectionSerializer(sections, many=True) return Response(serializer.data)
elif request.method == 'POST':
serializer = SectionSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
serializer_data = serializer.data
del serializer_data['id']
return Response(serializer_data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Field descriptions seems to work smoothly by declaring a serializer_class variable in class-based views that inherits APIView like this one:
class ObtainAuthToken(APIView): throttle_classes = () permission_classes = () parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) renderer_classes = (renderers.JSONRenderer,) serializer_class = AuthTokenSerializer
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key})
@Dean-Christian-Armada Did you solve this?
Actually no, I switched to class-based views
Ok. I imagine as there is not a serializers_class
decorator, neither a property that can be extracted from function based views, it's not possible get the fields description
Exactly, besides I found out that the class-based view is much better
I am working with the DRF and got struck at this point. I am using fuction based views , and I am not getting the details of input parameters in API doc page. Please help on this one , if someone came across it.
@niscp have you found a solution ?
So, if you are using a decorator like @api_view
, the pattern.callback
in rest_framework_docs.api_endpoint.py
will not be api_section
as you might suspect. But the callable api_view
which apparently doesn't contain a docstring.
So there is a way to get a docstring out of api_view
function however. It is written here:
http://stackoverflow.com/questions/1782843/python-decorator-handling-docstrings
Basically you need to rewrite api_view
in that way that it will contain a decorator functools.wraps()
which will update the attrs of the decorator.
like so:
from functools import wraps
def decorator(f):
@wraps(f)
def _decorator():
print 'decorator active'
f()
return _decorator
@decorator
def foo():
'''the magic foo function'''
print 'this is function foo'
help(foo)