【问题标题】:Django - how to access session status from templateDjango - 如何从模板访问会话状态
【发布时间】:2012-08-26 11:07:53
【问题描述】:

我想为索引页面上的每个帖子添加一个“编辑”链接。但在显示此链接之前;我需要检查会话是否已注册。我的意思是我需要这样的东西:

{% if session.name=='blabla' %}
    <a href="#">Edit</a>
{% endif %}

我在 模板上下文处理器上有 django.core.context_processors.request

谢谢

编辑:

这是我的详细页面视图:

def singlePost(request,postslug):
    post = get_object_or_404(Post, slug=postslug)
    context = {'post':post}
    return render_to_response('detail.html',context,context_instance = RequestContext(request))

当我尝试这个时:

def singlePost(request,postslug):
    session=request.session['loggedin']
    post = get_object_or_404(Post, slug=postslug)
    context = {'post':post}
    return render_to_response('detail.html',context,context_instance = RequestContext(request,{'session':'session',}))

它给出了模板语法错误(渲染错误)

我试过这个:

{% if request.session.name=='blablabla' %}

这是错误:

TemplateSyntaxError at /post/viva-barca

Could not parse the remainder: '=='djangoo'' from 'request.session.name=='djangoo''

【问题讨论】:

  • 如果您遇到错误,您应该包含完整的回溯。

标签: django django-templates django-sessions


【解决方案1】:

如果您使用的是django.core.context_processors.request,并且模板是使用RequestContext 呈现的,那么您可以通过请求访问会话。

{% if request.session.name == 'blabla' %}
    <a href="#">Edit</a>
{% endif %}

编辑:

RequestContextrender 快捷方式和通用视图自动使用。如果您使用的是render_to_response,则需要使用context_instance 参数传递。这在 RequestContext https://docs.djangoproject.com/en/1.4/ref/templates/api/#subclassing-context-requestcontext 的文档中有详细说明

【讨论】:

  • 渲染一个带有请求上下文的模板?你能解释一下吗?
  • 它没有用。我想我做错了。查看我的问题更新
  • 它没有用。没有错误。但没有用。我登录到管理页面。然后返回索引页面。但看不到“编辑”字符串。我已经添加了视图(第二个)
  • 您的视图中没有设置session['name']
  • 它现在工作了。但是当我注销时:键错误“名称”。它必须消失。
【解决方案2】:

我找到了另一种方式。

{% if post.owner == user %}

        <div class="right"><a href="{% url editpost post.id %}">Edit</a></div>

        {% endif %}

这样;我也可以控制用户身份验证。因为有很多用户拥有自己的帐户和帖子,它们都列在 index.html 中。如果我不写这个控件; x 用户可以编辑其他 y 用户的帖子。但现在只有登录用户才能编辑自己的帖子。

如果没有任何登录用户;未显示“编辑”链接。

【讨论】:

  • 您应该在视图文件中有用户模型的上下文,以便在模板文件中使用它。
猜你喜欢
  • 2011-02-02
  • 1970-01-01
  • 1970-01-01
  • 2011-10-17
  • 1970-01-01
  • 2019-01-01
  • 1970-01-01
  • 2014-11-26
相关资源
最近更新 更多