Reputation: 138
I am trying to update an existing record in Django but whenever I PUT request with postman I get the following.
It says that it already exists. So i tried to assign
task_1 = Task.objects.get(pk=task_id)
task_1 = ser
But I get an error that i can't assign it
===============================
class TaskView(APIView):
permission_classes = (IsAuthenticated,)
def put(self, request, task_id):
task_obj = find_task(request.auth, task_id)
if task_obj:
task = task_obj.data
my_data = json.loads(request.body)
keys = list(my_data.keys())
for key in keys:
task[key] = my_data[key]
ser = TaskSerializer(data=task)
ser.is_valid(raise_exception=True)
ser.save()
return Response(ser.data)
else:
return Response(status=status.HTTP_404_NOT_FOUND)
# Returns the task only if its assigned to current user
def find_task(token, task_id):
u_id = Token.objects.get(key=token).user_id
assign_to = AssignTo.objects.filter(task_id=task_id, user_id=u_id)
if len(assign_to) > 0:
task = Task.objects.get(pk=task_id)
serializer = TaskSerializer(task)
return serializer
else:
return False
I believe it has nothing to do with the method i use ( POST, PUT, PATCH) because it works perfect when I comment out this part of code:
# ser = TaskSerializer(data=task)
# print(ser)
# ser.is_valid(raise_exception=True)
# ser.save()
return Response(task)
So it's something with serialization and task Instances
===============================
def put(self, request, task_id):
u_id = Token.objects.get(key=request.auth).user_id
assign_to = AssignTo.objects.filter(task_id=task_id, user_id=u_id)
if len(assign_to) > 0:
task = Task.objects.get(pk=task_id)
my_data = json.loads(request.body)
keys = list(my_data.keys())
for key in keys:
task[key] = my_data[key]
print(task)
return Response(task)
else:
return Response(status=status.HTTP_404_NOT_FOUND)
The error I get from my SECOND VERSION of code is :
TypeError: 'Task' object does not support item assignment
So how do I update JUST the given keys from the request body.
Upvotes: 0
Views: 1628
Reputation: 138
So the solution was pretty simple.
I just had to add some args inside the save function => task.save(update_fields=keys)
This is my working code:
def put(self, request, task_id):
# task = Task.objects.get(pk=task_id)
# Task is the returned Model value
task = find_task(request.auth, task_id)
if task:
my_data = json.loads(request.body)
keys = list(my_data.keys())
for key in keys:
setattr(task, key, my_data[key])
task.save(update_fields=keys)
ser = TaskSerializer(task)
return Response(ser.data)
else:
return Response(status=status.HTTP_404_NOT_FOUND)
Upvotes: 1