1

我对 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 时,它​​会评估基本模板,就好像用户没有注册一样(在标题中显示登录),但它确实显示了配置文件结果。此外,静态文件也不能正常工作?

为什么会发生这种情况的任何线索?

ps 我已经在 settings.py 中包含了模板目录

谢谢你的帮助!

4

1 回答 1

1

正如 dm03514 在评论中所说,您将用户名 - 一个字符串 - 作为user变量传递给模板,而不是实际的用户对象。用户名字符串没有方法is_authenticated,因此您的检查返回 False。

事实上,您根本不应该将用户传递给模板上下文。相反,使用RequestContext,它使用上下文处理器将各种项目添加到上下文中 - 包括用户。

return render_to_response(template_name, {}, context_instance=RequestContext(request))
于 2011-09-30T13:58:57.063 回答