Search code examples
djangodjango-testing

How to test redirect if form.is_valid()


I've builded a view who posts data and redirect to contact/success. My problem is how to test the redirection with assertRedirects?

My Views.py:

def emailView(request):
    form = ContactForm(request.POST)
    if form.is_valid():
        gender = form.cleaned_data['gender']
        first_name = form.cleaned_data['first_name']
        last_name = form.cleaned_data['last_name']
        gender = request.POST['gender']
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        context = {
             'form': form,
        } 
    return redirect('success_contact')

'success_contact' is redirecting to URL 'contact/success'. In my tests.py I've tried achieve it this way:

 form_data = {'gender': '1, 'first_name': 'Luke',
              'last_name': 'Skywalker'}
 form = ContactForm(form_data)
 response = self.client.post('/contact', form_data)
 self.assertRedirects(response, '/contact/success/',
                      status_code=302, target_status_code=200)

Unfortunately I just got this AssertationError:

 Traceback (most recent call last):
 File 
 "/Users/user/Django/contactproj/contact/tests/test_views.py", line 126, in test_view_form_valid
target_status_code=200)
 File "/Users/user/anaconda3/envs/contactproj/lib/python3.6/site-packages/django/test/testcases.py", line 283, in assertRedirects
% (response.status_code, status_code)

AssertionError: 301 != 302 : Response didn't redirect as expected: Response code was 301 (expected 302)

Solution

  • You're posting to the wrong URL in your test, it should be /contact/ with a trailing slash. Even better, use the reverse() function to look up the URL.