django modifying the request object

PythonDjango

Python Problem Overview


I already have a django project and it logical like those:

url: URL?username=name&pwd=passwd

view:

def func(request):
   dic = request.GET
   
   username = dic.get("username")
   pwd = dic.get("pwd")

but now we need encrypt the data. Then, the request become this:

url: URL?crypt=XXXXXXXXXX (XXXXXXXX is encrypted str for "username=name&pwd=passwd")

so I need modify every view function. But now I want decrypt in django middleware to prevent from modifying every view function.

but when I modify request.GET, I recive error msg "This QueryDict instance is immutable". How can I modify it?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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.

Solution 3 - Python

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

Solution 4 - Python

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

Solution 5 - Python

You just have to change the request.data:

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

Solution 6 - Python

Currently, I have Django 3.2.2. I needed to modify self.request.query_params. I have read here in the comments that self.request.query_params is just a wrapper for self.request.GET.

First, I have tried the following:

self.request.GET = self.request.GET.copy()
... modify self.request.GET

But self.request.query_params hasn't changed.

When I tried explicitly self.request.query_params = self.request.GET or self.request.query_params = self.request.query_params.copy(), I got AttributeError: can't set attribute.

The only approach that worked:

self.request.query_params._mutable = True
self.request.query_params['attribute'] = 'needed_value'
self.request.query_params._mutable = False

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2801567View Question on Stackoverflow
Solution 1 - PythonFilip DupanovićView Answer on Stackoverflow
Solution 2 - PythonlaffusteView Answer on Stackoverflow
Solution 3 - PythonyuviView Answer on Stackoverflow
Solution 4 - PythonMohideen bin MohammedView Answer on Stackoverflow
Solution 5 - PythonHeenry GarciaView Answer on Stackoverflow
Solution 6 - PythonSerhii KushchenkoView Answer on Stackoverflow