I have a form in my site_base.html which extends to all of my templates.
In my site_base.html, there is a dropdown form which allows a user to change his role. Based on the selected role, the templates changes.
I've thought to persist this information via a context processor
but I'm having problems writing the right logic that will persist the form value.
So basically when a user has selected his role, I am using that role_id
to populate my urls but I can't do because I will be getting a null
value whenever I click on a new link thanks to my logic in the context_processor
.
I'm kinda new to Python and Django and I'm not sure how I should go about doing this?
The good use case in the wild would be Github's account context switcher.
form in 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>
naive 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}
Store the value in the session (in a view, not the context processor) as soon as it's set for the first time.
request.session['role_id'] = request.POST['role']
Then you can get the actual Role object in your context processor each time:
current_role = Role.objects.get(role_id=request.session['role_id'])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.