3

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mahbod_SN
  • 51
  • 1
  • 5

2 Answers2

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

abheet22
  • 470
  • 4
  • 12
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
  • 644
  • 7
  • 13
  • `def process_request(self, request): request.foo = 'bar' print(json.loads(request.body)) return None` I added this code but it didn't work. Request.body didn't change. – Mahbod_SN Sep 01 '18 at 12:50
  • please check my answer now, the tricky was I used `request.GET.copy()` method to handle modification in `request` – Sopan Sep 02 '18 at 11:08
  • Nope. Unfortunately this isn't work too. I'm new in django and yet this is mt problem. – Mahbod_SN Sep 08 '18 at 08:21
  • do you get any error? if yes - then please share that! – Sopan Sep 08 '18 at 10:43
  • No, It's just don't change. – Mahbod_SN Sep 10 '18 at 14:01
  • Try following: 1. Add some syntax error in your `example.SimpleMiddleware` code - see if you get error. This will confirm your code is enabled 2. Add `print` statement at every block and see if you get at least one line printed in console because above code. – Sopan Sep 10 '18 at 14:12