4

I have following code in my template:

<div class="account"> {% if request.user.is_authenticated %} <a href="{% url settings %}" class="iconed username">{{ request.user.username }}</a> &nbsp;|&nbsp; <a href="{% url logout %}?next={{ request.path }}" class="iconed logout">{% trans "Logout" %}</a> {% else %} <a href="{% url login %}?next={{ request.path }}" class="iconed login">{% trans "Login" %}</a> &nbsp;|&nbsp; <a href="{% url sign_up %}?next={{ request.path }}" class="iconed sign-up">{% trans "Sign up" %}</a> {% endif %} </div> 

As you can see, it shows different links depends on user logged in or not. It works fine if I test it by hands, but when I try to test it with following code:

def test_home_logged_in(self): if self.client.login(username='Test', password='secret'): home = self.app.get('/') self.assertOK(home) self.assertContains(home, '/settings/') self.assertContains(home, '/logout/') else: self.fail("Couldn't log in.") 

login() returns True, but test fails. I called showbrowser() for home object and see, that page that was returned, looks like page for anonymous user - it contains links to sign up and login besides links to settings and logout.

Is it correct to use *request.user.is_authenticated* in template to check if user is authenticated? Why template doesn't see that user was signed up from test?

Thanks!

2 Answers 2

13

Based on your other questions, I'm guessing you're using django_webtest. If so, you can specify to the request which user you want to be logged in as. So to access the homepage as user 'Test' you would do:

home = self.app.get('/', user='Test') 
Sign up to request clarification or add additional context in comments.

1 Comment

It works! I tried this method before, but send object as user. Thanks a lot, @Spike, you come to my help again!
2

It is correct, but you need to have django.core.context_processors.request in settings.TEMPLATE_CONTEXT_PROCESSORS to make request accessible from templates.

3 Comments

Thanks, @jkbr, but I already have this context processor in settings.TEMPLATE_CONTEXT_PROCESSORS. Problem appears only when I try to access template from test case.
What does self.app.get('/') do as opposed to self.client.get?
I forgot to write, that I use django_webtest as testing framework, sorry. Thanks for your reply, self.client.get('/') works fine after authentication.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.