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