Kurtis Nusbaum
Kurtis Nusbaum

Reputation: 30845

Test put method in Django

I'm testing a PUT method in my Django app. However, when I call:

payload = '{server_lib_song_id : -1, host_lib_song_id : ' + str(lib_id) + \
  ', song : "' + song + '", artist : "' + artist + '" , album : "' + \
 album +'"}'
response = client.put('/udj/users/' + user_id + '/library/song', \
  data=payload, content_type='text/json', \
  **{'udj_ticket_hash' : ticket_hash})

in my test I get the following error in my view:

AttributeError: 'FakePayload' object has no attribute 'readline'

The line which is throwing this error is:

payload = request.readlines()

So how to I ensure that the actual payload I sent with my put request (not a FakePayload object) is what gets to the code I'm trying to test in my view?

Upvotes: 1

Views: 1880

Answers (2)

guyrt
guyrt

Reputation: 927

I would caution against hacking your production code for a test error like this. It almost always means that you are doing something wrong, which you should fix. In my case, the cause of this bug was initializing a form with the request object, not request.POST or request.GET. If you are still experiencing this bug (let's hope not...), re-examine your form initialization or post it here.

Upvotes: 0

Kurtis Nusbaum
Kurtis Nusbaum

Reputation: 30845

So the way to actually go about this is to use the raw_post_data function. This is a shame because as far as I can tell, this breaks the REST model. But hey, it works.

I essentially changed:

payload = request.readlines()

to:

   payload = request.raw_post_data

in my view.

Upvotes: 1

Related Questions