2
我在我的site_base.html中有一個表單,它擴展到了我的所有模板。Django上下文處理器和表單變量
在我的site_base.html中,有一個允許用戶更改角色的下拉表單。基於選定的角色,模板會更改。
我以爲通過context processor
堅持這個信息,但我有問題寫入正確的邏輯,將持續的形式價值。
因此,基本上,當用戶已經選擇了自己的角色,我使用的role_id
來填充我的網址,但我不能這樣做,因爲我會得到一個null
值,每當我一個新的鏈接,點擊感謝我的邏輯context_processor
。
我對Python和Django有點新鮮,我不知道我應該怎麼做呢?
在野外的好用例是Github的帳戶上下文切換器。
在site_base.html
123 <form name="context" method="post" action="">{% csrf_token %}
124 <div class="input_group">
125 <select name="role" onchange="contextform();">
126 <option value="none">Select Context</option>
127 {% for role in request.user.get_or_create_profile.roles.all %}
128 <option value="{{ role.id }}" {% ifequal role.id current_role.id %}selected="selected"{% endifequal %}>{{ role.name }} for {{ role.event }}</option>
129 {% endfor %}
130 </select>
131 </div>
132 {{ current_role }}
133 </form>
幼稚context.processor.py
3 def context_switcher(request):
4 """
5 Get a user's role
6 """
7 if 'role' in request.POST:
8 role_id = request.POST.get('role')
9 current_role = Role.objects.filter(id=role_id)[0]
10 else:
11 current_role = ''
12 return {'current_role': current_role}
是..這是我在做什麼現在..除非我正在考慮使用中間件將用戶的狀態存儲在會話中而不是上下文處理器或視圖中。原因是因爲用戶的入口點可能不是我首先設置會話變量的視圖。 – super9