How can I have the django message framework work with the rest_framework?
Here is my view
@api_view(['GET', 'POST'])
def myview(request):
if request.method == 'GET':
#return a Response object
else:
#process post data
messages.success(request, 'Success')
return Response(response)
I encounter the following error
add_message() argument must be an HttpRequest object, not 'Request'
which is because the rest_framework
does not use the normal HttpRequest
object, used
in django by default.
How can I use messaging framework with rest framework?
Import messages from django. contrib at the top of the file then go to the view function where you wish to add the message(s). In this case, it's a contact view that needs a Django success message and a Django error message. Add a success message just before the return redirect ("main:homepage") stating "Message sent."
The messages framework allows you to temporarily store messages in one request and retrieve them for display in a subsequent request (usually the next one). Every message is tagged with a specific level that determines its priority (e.g., info , warning , or error ).
REST framework provides an APIView class, which subclasses Django's View class. APIView classes are different from regular View classes in the following ways: Requests passed to the handler methods will be REST framework's Request instances, not Django's HttpRequest instances.
The browsable API feature in the Django REST framework generates HTML output for different resources. It facilitates interaction with RESTful web service through any web browser. To enable this feature, we should specify text/html for the Content-Type key in the request header.
DRF views do not use HttpRequest
but use rest_framework.request.Request
, (read here) you can access to the object that you need using
messages.success(request._request, 'Success')
anyway this code have sense only if you are using BrowsableAPIRenderer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With