2017-07-14 49 views
-1

(Django,Python)我已經創建了一個書對象列表,它在我的views.py中作爲上下文與當前會話一起傳遞。在我的模板上,我將檢查該列表中的書是否存儲在會話中,如果他們是我想在該會話中訪問與該書有關的某些信息。我如何動態訪問會話中的書籍?有沒有辦法?如何使用django動態訪問會話中的值?

我知道我可以通過使用「request.session.name」訪問這些文件(其中「名」是同它存儲在會話中的空間)

有保存在會話幾個書名,他們被保存的方式如下(在views.py下的函數中)

request.session [「random book title」] =「隨機美元價格」 我想要動態訪問「隨機美元價格」在模板中。

這是代碼塊模板

{% for book in book_list %} 
    {% if book.title in request.session %} 
      {{ request.session.??? }}      
    {% endif %} 
{% endfor %} 

預先感謝您!

回答

0

您可以自定義模板標籤通過屬性來查找喜歡這裏 Performing a getattr() style lookup in a django template

# app/templatetags/getattribute.py 

import re 
from django import template 
from django.conf import settings 

numeric_test = re.compile("^\d+$") 
register = template.Library() 

def getattribute(value, arg): 
    """Gets an attribute of an object dynamically from a string name""" 

    if hasattr(value, str(arg)): 
     return getattr(value, arg) 
    elif hasattr(value, 'has_key') and value.has_key(arg): 
     return value[arg] 
    elif numeric_test.match(str(arg)) and len(value) > int(arg): 
     return value[int(arg)] 
    else: 
     return settings.TEMPLATE_STRING_IF_INVALID 

register.filter('getattribute', getattribute) 

現在改變你模板到

{% load getattribute %} 

{% for book in book_list %} 
    {% if book.title in request.session %} 
      {{ request.session|getattribute:book.title }}      
    {% endif %} 
{% endfor %} 

這是一個基本的自定義模板Ë標記示例:

Django - Simple custom template tag example

和文檔:

https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/

從我從我的Django的日子記得應該工作

+0

完美!這似乎更喜歡它......謝謝你!我會給這個嘗試,並會讓你知道 – cahg88

+0

雅django模板是有限的,我現在使用瓶api/reactjs應用程序:) – codyc4321

1

您可以將會話數據放入字典中,並在需要在視圖函數中呈現該數據時將此數據發送到目標模板。

def some_function(request): 
     context={ 
      'data':sessionData #put session data here 
     } 
     return render(request,"pass/to/template.html",context) 

現在你可以在你的template.html訪問「數據」

+0

這是在我的功能已經完成,我想do是在模板中動態訪問值...我知道我可以通過「request.session。」名稱訪問值,但我不想硬編碼「名稱」,我想動態地做到這一點......是否有一個辦法? – cahg88

+0

你是什麼意思動態?你能再解釋一下嗎? – pooya

+0

他需要迭代像'request.session.adventures_of_harkon','request.session.book_of_narnia'等模板,其中'book_of_narnia'等實際上來自'book.title' – codyc4321