Marboni
Marboni

Reputation: 2459

User authentication in django_webtest

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!

Upvotes: 4

Views: 1655

Answers (2)

Spike
Spike

Reputation: 5130

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')

Upvotes: 13

Jakub Roztocil
Jakub Roztocil

Reputation: 16252

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

Upvotes: 2

Related Questions