[Django]-This QueryDict instance is immutable

93πŸ‘

As you can see in the Django documentation:

The QueryDicts at request.POST and request.GET will be immutable when accessed in a normal request/response cycle.

so you can use the recommendation from the same documentation:

To get a mutable version you need to use QueryDict.copy()

or … use a little trick, for example, if you need to keep a reference to an object for some reason or leave the object the same:

# remember old state
_mutable = data._mutable

# set to mutable
data._mutable = True

# сhange the values you want
data['param_name'] = 'new value'

# set mutable flag back
data._mutable = _mutable

where data it is your QueryDicts

22πŸ‘

Do Simple:

#views.py
from rest_framework import generics


class Login(generics.CreateAPIView):
    serializer_class = MySerializerClass
    def create(self, request, *args, **kwargs):
        request.data._mutable = True
        request.data['username'] = "example@mail.com"
        request.data._mutable = False

#serializes.py
from rest_framework import serializers


class MySerializerClass(serializers.Serializer):
    username = serializers.CharField(required=False)
    password = serializers.CharField(required=False)
    class Meta:
        fields = ('username', 'password')
πŸ‘€CPMaurya

9πŸ‘

request.data._mutable=True

Make mutable true to enable editing in querydict or the request.

πŸ‘€vaishnavi

4πŸ‘

You can use request=request.copy() at the first line of your function.

3πŸ‘

I personally think it would be more elegant to write code like this.

def create(self, request, *args, **kwargs):
    data = OrderedDict()
    data.update(request.data)
    data['account'] = request.user.account
    serializer = self.get_serializer(data)
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
πŸ‘€zmaplex

2πŸ‘

Do you know any better way to add additional fields when creating an object with django rest framework?

The official way to provide extra data when creating/updating an object is to pass them to the serializer.save() as shown here

πŸ‘€Linovia

1πŸ‘

https://docs.djangoproject.com/en/2.0/ref/request-response/#querydict-objects

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

πŸ‘€kevin wong

Leave a comment