How to perform a Django test with a



I’m using Django 1.8 and Python 3.5.

I have a view method I would love to test. I am supplying the self.client.get method with the data but it fails to validate the form. what am I doing wrong?

This is the view method:

def saveNewDriverInfo(request):
    if  request.user.is_authenticated():
        form = DriverForm(request.POST)  
        if  form.is_valid():
            new_Driver =
            carid = form.cleaned_data['carID']
            Car = get_object_or_404(Car, pk=carid)
            return redirect('carmanager:carDetails', carID=carid
            return HttpResponse("something went wong some where! yes i said wong!")

This is the test method:

 def test_saveNewDriverInfo(self):
response= self.client.get(reverse('carmanager:saveNewDriverInfo'),data={'form':{'carID':'1034567','Driver_Last_Name':'daddy','Driver_First_Name':'daddy','Driver_Middle_Initial':'K','entered_by':'king'}})
            #self.assertRedirects(response, expected_url, status_code, target_status_code, host, msg_prefix, fetch_redirect_response)
            self.assertNotContains(response, 'something went wrong' ,200)

Also, note that this test works because it gets the response. But the line that is commented out is what I want to use.

However, I cant seem to feed the information to the DriverForm. Any help will be greatly appreciated.


You should use, data) in your test, since your view is looking for the POST data (request.POST) and not for request.GET.

I’d also suggest to refactor your view to match the template given here:

I am a little confused by the way your test passes data to self.client.get. Assuming your form has the fields carID, Driver_Last_Name, etc, the call to self.client.get should look like self.client.get(url, data={'carID': <id>, 'Driver_Last_Name': <driver_last_name>, ...}). The 'form' key should not be needed. The same goes for See also here:

Answered By – Martin Bierbaum

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More