Debugging PUT Method
After following along with a tutorial video using the Django framework, I decided to test some of the functionality of the code I’ve been working on. The GET and POST methods worked as expected. But while testing the PUT method, the code began to throw some errors. I would like to share what problems I encountered and show how I ultimately resolved them.
Here is what the code initially looked like:
This is the exception that was thrown: “User() got unexpected keyword arguments: ‘data’ ” After looking through the stack trace, I found that it was specifically line 33 that caused the problem. Although it is pretty obvious what the problem is in retrospect, it wasn’t so clear at that moment.
Get Matev Ivan’s stories in your inbox
Join Medium for free to get updates from this writer.
The following was the process I used to debug. First, I added a print statement just before line 33 to see what the value of the user was. For the remainder of the example, let us use “John Smith” for the name and 23 for the age. The print statement returned: “John Smith” I wasn’t sure why only the name was returned and not the user object as a whole. When I opened up the User object, I saw there was a default return method that was set to return the name of the user. This seemed to be working correctly. But I changed the return statement to be more aesthetic. Either way, this meant that I was selecting the correct user but was still throwing that exception.
Next, I looked at the POST method because the PUT method has some similarities in its functionality. In the POST method, the line with the serializer looked like this: serializer = UserSerializer(data=request.data) This code immediately revealed the issue in my code. The serializer variable in the PUT method code was set to a User object rather than a UserSerializer object.
This simple fix resolved the expectation, and it was no longer thrown. I will continue to touch on the project to grow in my understanding of the Django framework. Here is the link to the repository on GitHub if you are curious and want to take a look at the code yourself: https://github.com/MatevIvan/DjangoPractice



