如何根据用户登录django在模板中显示不同的按钮

时间:2012-09-12 09:24:46

标签: django django-templates django-views

我需要根据用户的登录信息在模板中显示不同的按钮。该方案是我的模板显示跟随按钮:

Check whether the user logged in or not-
  if user logged in-
   check which channel he follwed:
     if he followed any channel 
       beside that channel name show "followed" button
     else
       show "follow" button with the path follow_save 
  elif user not logged in:
     show follow button with the path follow_save

我被困在怎么办?这是视图或模板的任务吗?怎么做?你的任何帮助专家都会救我。我也想从会话中获取user_id。 这是我的views.py

e= EventArchiveGallery.objects.all()   
user = request.session['user_id']
if user:
    j = EventArchiveGallery()
    joining_list = j.joiningList(user)         

return render_to_response('gallery/allevents.html',
{
    'joining_list':joining_list,
},
context_instance=RequestContext(request)                         
) 

这是我的模板:

{% for event in live %}
    <p>Event Title:{{event.event_title}}<p/>
    <p>Channel Name:{{event.channel_id.channel_title}}</p>
    <p>Event Description{{event.event_description}}</p>
    {% if event in joining_list %}
        <p>followed</p>
            {%else%}
                    <p>follow</p> #I have wanted to show follow_save function call from this button,when user clicked
            {endif%}
  {% endfor %}

1 个答案:

答案 0 :(得分:0)

如果你可以分成2个问题,你会更好地提出2个问题......

  • 根据用户的登录信息在我的模板中显示不同的按钮
    • 更好的方法是识别要在视图中显示的内容并将上下文参数传递给模板。根据此变量模板将呈现不同的HTML。

示例模板:假设视图传递followed_channel参数。

{% if user.is_authenticated %}
    {%if followed_channel %}
        {# render html you want #}
    {%else%}
        {# render another way #}
    {%endif%}
{%endif%}
  • 此外,我还想从会话中获取user_id

在您离开会话之前,您必须存储它。因此,您可以将视图更新为

e= EventArchiveGallery.objects.all()   
user = request.session.get('user_id')
if not user:
     request.session['user_id'] = request.user.id
if user:
    j = EventArchiveGallery()
    joining_list = j.joiningList(user)         

return render_to_response('gallery/allevents.html',
{
    'joining_list':joining_list,
},
context_instance=RequestContext(request)                         
)