3

I am writing a test for a post view. It does work, But when I try and post to it with APIClient.post, I get QueryDict: {}. Here is the test:

class SMSCreateData(APITestCase):
...
    def test_SMS(self):
        ...
        postData = {'Body': string, 'From': phNum.phone_number}
        self.client.post(reverse('SMS-data'), postData)

And here is the view:

def SMSSubmitDataPointView(request):
...
    try:
        print request.POST
...
SillyInventor
  • 113
  • 1
  • 11

1 Answers1

5

urlencode your post data and set content_type to application/x-www-form-urlencoded.

from urllib.parse import urlencode  
# In python 2, use this instead: from urllib import urlencode  


response = self.client.post(reverse('SMS-data'), urlencode(postData),
    content_type='application/x-www-form-urlencoded'
)

You will get data in request.POST

Scott Stafford
  • 43,764
  • 28
  • 129
  • 177
Satendra
  • 6,755
  • 4
  • 26
  • 46
  • I guess you are using client.get method in other places. `request.POST` Only handles form data. http://www.django-rest-framework.org/tutorial/2-requests-and-responses/ – Satendra May 09 '18 at 04:28
  • If you don’t provide a value for content_type, the values in data will be transmitted with a content type of multipart/form-data. https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.Client.post – Satendra May 09 '18 at 04:31