Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using django message framework with rest_framework

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?

like image 737
rjv Avatar asked Dec 13 '14 06:12

rjv


People also ask

How do I use Django message 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."

What is messages framework in Django?

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 ).

What is @api_view in Django?

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.

What is Django browsable API?

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.


1 Answers

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

like image 63
sax Avatar answered Sep 19 '22 17:09

sax