Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add field to request body in django middleware

I want to add new field in request body in middleware and use it in views.

I googled it but the results was not worked.

How can I do it?

Django v2 python 3.6

like image 915
Mahbod_SN Avatar asked Sep 03 '25 04:09

Mahbod_SN


1 Answers

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.

like image 57
Sopan Avatar answered Sep 04 '25 23:09

Sopan