[Django]-How can I add field to request body in django middleware

2👍

You need to add a separate custom middleware which will process the request before landing to a particular view. Below is the code for custom middleware:

class ProcessRequestMiddleware(MiddlewareMixin):
    """
    This middleware appends new payload in request body
    """

    def process_view(self, request, view_func, *view_args, **view_kwargs):
        request_data = getattr(request, '_body', request.body)
        request_data = json.loads(request_data)
        # here you can write the logic to append the payload to request data
        request._body = json.dumps(request_data)
        return None

Note – The middleware was place inside an app common (common/middleware/custommiddleware.py)

Now add this middleware to settings.MIDDLEWARE list:

"common.middleware.custommiddleware.ProcessRequestMiddleware"

Now you can retrieve the payload, which you had appended in custommiddleware, inside any of the views you want by just calling the json.loads(request.body).

1👍

Try following code:

class SimpleMiddleware:
def __init__(self, get_response):
    self.get_response = get_response

def __call__(self, request):
    my_request  = request.GET.copy()
    my_request['foo']='bar'
    request.GET = my_request
    response = self.get_response(request)
    return response

I tried this for you: added above code into: example.py Then added 'example.SimpleMiddleware', into MIDDLEWARE

My view method:

def index(request):
    for key in request.GET:
         print (key, '--->', request.GET[key])
    return render(request, 'example.html')

able to print foo ---> bar browser sends the request.

👤Sopan

Leave a comment