[Django]-Django modifying the request object

130👍

django.http.QueryDict objects that are assigned to request.GET and request.POST are immutable.

You can convert it to a mutable QueryDict instance by copying it:

request.GET = request.GET.copy()

Afterwards you’ll be able to modify the QueryDict:

>>> from django.test.client import RequestFactory
>>> request = RequestFactory().get('/')
>>> request.GET
<QueryDict: {}>
>>> request.GET['foo'] = 'bar'
AttributeError: This QueryDict instance is immutable
>>> request.GET = request.GET.copy()
<QueryDict: {}>
>>> request.GET['foo'] = 'bar'
>>> request.GET
<QueryDict: {'foo': 'bar'}>

This has been purposefully designed so that none of the application components are allowed to edit the source request data, so even creating a immutable QueryDict again would break this design. I would still suggest that you follow the guidelines and assign additional request data directly on the request object in your middleware, despite the fact that it might cause you to edit your sources.

68👍

Remove immutability:

if not request.GET._mutable:
   request.GET._mutable = True

# now you can spoil it
request.GET['pwd'] = 'iloveyou'

Update

The Django sanctioned way is: request.GET.copy().

According to the docs:

The QueryDicts at request.POST and request.GET will be immutable when accessed in a normal request/response cycle. To get a mutable version you need to use QueryDict.copy().

Nothing guarantees future Django versions will use _mutable. This has more chances to change than the copy() method.

9👍

You shouldn’t use GET to send the username and password, it’s bad practice (since it shows the information on the URL bar, and might pose a security risk). Instead, use POST. Also, I’m guessing you’re trying to authenticate your users, and it seems like you’re doing too much work (creating a new middleware) to deal with something that is completely built in, to take the example from the docs:

from django.contrib.auth import authenticate, login

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            # Redirect to a success page.
        else:
            # Return a 'disabled account' error message
    else:
        # Return an 'invalid login' error message.

I myself really like using the login_required decorator, very simple to use. Hope that helps

4👍

request.GET._mutable = True

you need this.

def func(request):
   dic = request.GET
   request.GET._mutable = True #to make it editable 
   username = dic.get("username")
   request.GET.pop("pwd")
   request.GET._mutable = False #make it False once edit done

0👍

You just have to change the request.data:

def func(request):
   request.data._mutable = True
   dic = request.data
   username = dic['username']
   pwd = dic['pwd']

Leave a comment