django_webtest 中的用户身份验证
我的模板中有以下代码:
<div class="account">
{% if request.user.is_authenticated %}
<a href="{% url settings %}"
class="iconed username">{{ request.user.username }}</a>
|
<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>
|
<a href="{% url sign_up %}?next={{ request.path }}"
class="iconed sign-up">{% trans "Sign up" %}</a>
{% endif %}
</div>
如您所见,它显示不同的链接取决于用户是否登录。如果我手动测试它,它工作正常,但是当我尝试使用以下代码测试它时:
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() 返回 True,但测试失败。我为 home 对象调用了 showbrowser() ,看到返回的页面看起来像匿名用户的页面 - 除了设置和注销的链接之外,它还包含注册和登录的链接。
在模板中使用 *request.user.is_authenticated* 来检查用户是否经过身份验证是否正确?为什么模板看不到该用户是从 test 注册的?
谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据您的其他问题,我猜测您正在使用 django_webtest。如果是这样,您可以向请求指定您想要以哪个用户身份登录。因此,要以用户“测试”身份访问主页,您可以执行以下操作:
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:
这是正确的,但您需要有 django.core.context_processors.request href="https://docs.djangoproject.com/en/dev/ref/settings/#std%3asetting-TEMPLATE_CONTEXT_PROCESSORS" rel="nofollow">
settings.TEMPLATE_CONTEXT_PROCESSORS
使可从模板访问请求
。It is correct, but you need to have
django.core.context_processors.request
insettings.TEMPLATE_CONTEXT_PROCESSORS
to makerequest
accessible from templates.