我对Django很新,我只是用django-registration设置了我的第一个注册页面,一切运行良好(用户可以注册,更改密码等)。现在我想扩展我的应用程序,所以我想添加一个简单的个人资料页面,以便当用户登录时他/她可以看到他们的个人资料。所以我创建了一个profile_page.html模板来扩展基本模板,并在我的视图中设置了一个非常简单的视图:
@login_required
def profile_info_view(request, template_name='profile/profile_page.html'):
user_profile = request.user.username
return render_to_response(template_name,{ "user":user_profile })
我的基本模板如下所示:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="stylesheet" href="{{ STATIC_URL }}css/style.css" />
<link rel="stylesheet" href="{{ STATIC_URL }}css/reset.css" />
{% block extra_head_base %}
{% endblock %}
<title>{% block title %}User test{% endblock %}</title>
</head>
<body>
<div id="header">
{% block header %}
{% if user.is_authenticated %}
{{ user.username }} |
<a href="{% url auth_password_change %}">{% trans "Profile" %}</a> |
<a href="{% url index %}">{% trans "Home" %}</a> |
<a href="{% url auth_logout %}">{% trans "Log out" %}</a>
{% else %}
<a href="{% url auth_login %}">{% trans "Log in" %}</a> | <a href="{% url registration_register %}">{% trans "Sign up" %}</a>
{% endif %}
{% endblock %}
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
并且profile_pages.html模板为:
{% extends "base.html" %}
{% load i18n %}
{% block content %}
Hi, {{ user }}
{% endblock %}
和url.py:
urlpatterns = patterns('',
(r'^accounts/', include('registration.urls')),
(r'^profile/', profile_info_view),
(r'^$', direct_to_template,{ 'template': 'index.html' }, 'index'),
)
urlpatterns += staticfiles_urlpatterns()
所以我希望它是当登录用户进入个人资料页面(example.com/profile/)时,如果用户尚未登录,则会显示个人资料页面和登录页面。
但是当登录用户转到/ profile时,它会评估基本模板,就好像用户尚未注册(显示登录标题),但它确实显示了配置文件结果。而且静态文件也不起作用?
为什么会发生这种情况的任何线索?
P.S。我在settings.py
中包含了模板dirs感谢您的帮助!
答案 0 :(得分:1)
正如dm03514在评论中所说,您将用户名 - 字符串 - 作为user
变量传递给模板,而不是实际的用户对象。用户名字符串没有方法is_authenticated
,因此您的检查返回False。
实际上,您根本不应该将用户传递给模板上下文。相反,使用RequestContext,它使用上下文处理器向上下文添加各种项目 - 包括用户。
return render_to_response(template_name, {}, context_instance=RequestContext(request))