I’m a new hobbyist-level web programmer, working on my own projects. I’m by no means an expert, so I thought I’d ask the experts for advice.
I need to pass data from a template, which uses radio buttons to set a parameter, to a view. The HTML looks like this:
<form method="POST" action="set_power_level{{value}}">
{% csrf_token %}
<input type="radio" name="normal" id="power" value="Normal">
<label for="power" id="Normal">Normal</label><br>
<input type="radio" name="heroic" id="power" value="Heroic">
<label for="power" id="Heroic">Heroic</label><br>
<input type="radio" name="epic" id="power" value="Epic">
<label for="power" id="Epic">Epic</label><br>
<input type="radio" name="superhuman" id="power" value="Superhuman">
<label for="power" id="Superhuman">Superhuman</label><br>
</form>
... etc ... etc ...
<form method="POST" action="{% url 'choose_genre' %}">
{% csrf_token %}
<button>Next</button>
</form>
This is rendered by the following view:
def choose_power_level(request):
context = {}
if request.method == "POST":
request.session['campaign_power_level'] = ""
template = loader.get_template('htdocs/choose_power_level.html')
return render(request, 'htdocs/choose_power_level.html', context=context)
In the above code snippets, the page is displayed correctly and I can navigate forward and back through the various pages.
Clicking on the Next button needs to save the user’s choice, then render the next page on which the choice has to be displayed. The choice must also be available in later views.
My research indicates that sessions are the way to go and one example is:
Let’s say you have and argument variable called ‘test’ and the value is 123. The following code will assign that to your session variables list.
request.session[‘test’] = 123
Now you can browse the whole website it is still going to be available. Write the following code in ANY view to capture the value of test:
test = request.session[‘test’]
This is all well and good if the designer knows the value of the ‘test’ variable and can include it in a view. But I am using a radio button for the user to specify the value of ‘test’. I think my questions boil down to:
- How can this radio button choice be saved in a session variable and accessed later?
- Are sessions appropriate here or should I be using context instead?
I do understand this question has been asked an answered before (I’ve been all over Stack Overflow) but nothing seems to answer the radio button choice mechanism I’m using.
Kind Regards,
Colin