Search code examples
django-formsdjango-testing

GET Formset returns 302 instead of 200 (django)


I have used the inlineformset, the views method is as follows:

@login_required
def patron_edit_phone(request, *args, **kwargs):
    patron = request.user
    PhoneNumberFormSet = inlineformset_factory(Patron, PhoneNumber, extra=1, exclude="kind",can_order=True)
    if request.method == "POST":
        formset = PhoneNumberFormSet(request.POST, request.FILES, instance=patron)
        if formset.is_valid(): 
            formset.save()
            messages.success(request, _(u"Votre information de numéro de téléphone a bien été mise à jour"))
    else:
        formset = PhoneNumberFormSet(instance=patron)

    return direct_to_template(request, 'accounts/patron_phone_edit.html', extra_context={'formset': formset, 'patron': patron })

I have succeeded to test the "post" method for the inlineformset. Here is the code.

def test_patron_phone_edit(self):
        self.client.login(username='[email protected]', password='alex')
        response = self.client.post(reverse('patron_edit_phone'), {
            'phones-TOTAL_FORMS': u'1',
            'phones-INITIAL_FORMS': u'',
            'phones-MAX_NUM_FORMS': u'',

            'phones-0-id' : '1',
            'phones-0-patron' : '1',
            'phones-0-number' : "11111111", 
            'phones-0-DELETE' : u''
    })
    self.assertEquals(response.status_code, 200)
    patron = Patron.objects.get(email='[email protected]')
    for phone in patron.phones.all():
        if phone.id == 1:
            self.assertEquals(phone.number, "11111111")
        else:
            pass  

I have tried the following with the get method:

def test_patron_phone_get_form(self):
        self.client.login(usernamer='[email protected]', password='alex')

        response = self.client.get(reverse('patron_edit_phone'))

        self.assertEquals(response.status_code, 200)

But this doesn't work. Instead of getting a status_code=200, I get a status_code=302. Why? Perhaps I need to specify the total forms for the GET method?

Any help is highly appreciated!Thanks!

If more information is needed, leave a comment, then I will paste the needed information.


Solution

  • You have a typo in the login function. usernamer should be username. You're getting a 302 redirect sending you to the login page.