简体   繁体   中英

Django request context is None when it shouldn't be

I am busy extracting some authentication logic into a reusable app. In some of my views I redirect to the home page. As the homepage is only defined in the "host" Django project, I made a little fake:

urlpatterns = patterns(
    '',
    url(r'^sign_up/', views.sign_up, name='sign_up'),

)

if settings.UNIT_TEST_SETTINGS:
    def mock_home(request):
        return HttpResponse('mock home view for redirects')

    urlpatterns.append(url(r'^$', mock_home))

However my test that previously passed prior to extracting is now failing, as the request context is coming through as None.

@patch('auth_backend.forms.KagisoUser', autospec=True)
def test_sign_up_post(self, MockKagisoUser):  # noqa
    mock_user = MockKagisoUser.return_value
    mock_user.id = 1
    mock_user.save.return_value = mock_user

    data = {
        'email': 'bogus@email.com',            
        'password': 'mypassword',           
    }

    response = self.client.post('/sign_up/', data, follow=True)

    message = list(response.context['messages'])[0].message <<< NoneType object is not subscriptable

    assert response.status_code == 200
    assert mock_user.save.called

The code being tested is this snippet here:

@never_cache
@csrf_exempt
def sign_up(request):
   if request.method == 'POST':
        form = forms.SignUpForm.create(
            post_data=request.POST,            
        )

        if form.is_valid():
            try:
                user = form.save()
            except IntegrityError:
                messages.error(request, 'my error message')
                return HttpResponseRedirect(reverse('sign_in'))

            _send_confirmation_email(user, request)
            messages.success(request, 'Thanks for signing up)
            return HttpResponseRedirect('/')
    else:
        form = forms.SignUpForm.create()

    return render(
        request,
        'auth_backend/sign_up.html',
        {'form': form},
    )

This is the error I get: TypeError: 'NoneType' object is not subscriptable . I digged in a little and the whole context is None

Why is request.context None?

If the post request is successful, you are redirecting to your view mock_home .

Since you are returning HttpResponse('mock home view for redirects') for this view, there is no template or template context, so request.context is None .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM