pythondjangotestingviewapiclient

Django APIClient Post Empty


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

Solution

  • 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