How to check context and session in Django after redirect?

I have a view that looks like this:

def login(request): ... # some variables has been set here ... if request.POST.get('remember_me', None): request.session.set_expiry(1209600) # 2 weeks return HttpResponseRedirect(reverse('dashboard')) 

Now, if I argue for variables using the context, I get the error: "AttributeError object:" HttpResponseRedirect "does not have a context attribute," this is the same for sessions. How can I check it then that some variables have been set, and is it possible for the session to expire even if I redirect?

+6
django
source share
2 answers

You cannot get context variables from an HttpResponseRedirect . It doesn't make sense why you set context variables if you redirect anyway.

You should certainly be able to select variables from the session after the redirect. I did this in several of my tests. How do you approve session data in a test case?

Here's how I talk about asserting session variables after a redirect:

 response = self.client.post(reverse('foo')) self.assertRedirects(response, reverse('bar', args = ['baz']), status_code = 302, target_status_code = 200) self.assertEqual('value', self.client.session.get('key')) 

Self.client is an instance of django.test.client.Client in this case.

Update

(In response to @Marconi's comment) Here is one way to display a message to a user after a redirect. This is copied almost verbatim from my answer to another question .

Your first view can create a message for the current one using auth, and the second read will read and delete it. Something like that:

 def first_view(request, *args, **kwargs): # all goes well message = _("<message for user>") request.user.message_set.create(message = message) return redirect('second_view') def second_view(request, *args, **kwargs): # Render page # Template for second_view: {% for message in messages %} ... {% endfor %} 

Messages are stored in the database. This means that you can access them even after redirecting. They are automatically read and deleted when the template is rendered. You will need to use RequestContext .

+5
source share

What I did (specifically for session verification) is to not use the Django test client and create my own request object and pass it directly to my view, for example:

 def test_method(self): class request(object): POST = {'dummy':'data'} class session: @staticmethod def set_expiry(nmbr): request.session.nmbr = nmbr views.login(request) self.assertEqual(request.session.nmbr, 1209600) 

Another option would be to use the argument "follow = True" when using the Django testing client.

+1
source share

All Articles