Storing variables with sessions django - python

This is my code:
views.py:
def some_function(request):
form = MyForm(request.POST)
if request.method == 'GET':
return render_to_response('template.html', RequestContext(request, {'form': form}))
elif request.method == 'POST':
input_word = request.POST['input_word']
if 'word_choice' in request.POST:
word_choice = request.POST['word_choice']
else:
word_choice = ''
var1 = HelperClass(input_word).func1()
table1 = HelperClass(input_word).table_one()
table2 = HelperClass(input_word).table_two()
word_selected = word_choice
content = {
'form': form,
'input_word': input_word,
'var1': var1,
'table1' : table1,
'table2' : table2,
'word_selected': word_selected,
}
return render_to_response('result_template.html', RequestContext(request, content))
else:
raise Http404
This is result_template.html:
{% block content %}
<form action="/admin/find-word/" method="post">
{% csrf_token %}
<input id="input_word" type="text" name="input_word" maxlength="100"><br />
<input type="submit" value="Submit" />
<form />
<h1>{% trans "You entered" %} "{{ input_word }}" </h1>
<p>{{ var1 }}</p>
<form action="/admin/find-root/" method="post">
{% csrf_token %}
<h3>{% trans "Table2" %}</h3>
{% for word in table2 %}
# Get info from database and display it on the current template.
<input type="radio" name='word_choice' value="{{ word }}"> {{ word }}<br>
{% endfor %}
<h3>{% trans "Table3" %}</h3>
{% for word in table3 %}
{# Get info from database and display it on the current template. #}
<input type="radio" name='word_choice' value="{{ word }}"> {{ word }}<br>
{% endfor %}
<p>{% trans "You selected: " %}{{ word_selected }}</p>
{# Submit the word of choice.#}
<input type="submit" value="Search">
<form />
{% endblock %}
I need to add code to views.py, so that:
it shows result, that was rendered after submitting the first form
(when assining input_word)
new result shows, when resubmitting the first form
when submitting second form redirect to success_template.html (this part I can do myself)
I know, that I need to use sessions here. I've tried different things, but I'm lost now.

Create a session variable in django as follows.
request.session['key'] = value
Access it by
request.session['key'] # or
request.session.get('key')
remove it by
del request.session['key']

In django you can simply assign values to sessions with:
request.session['value']
In your case you'd have to replace the word_selected variable with request.session['word_selected']

Related

save check box to Boolean field in django using hand written form

Hi trying to save checkbox value on submit. The form displays the value correct. When value is True is, its checked and when false its unchecked. However I just can't get it to save on POST.
views.py
#login_required(login_url='login') def engine(request):
eng= Player.objects.filter(customer=request.user.customer)
isa= Customer.objects.filter(name=request.user.customer)
if request.method == "POST":
customer=request.user.customer
isa =
Customer.objects.filter(name=request.user.customer)
.update(is_active=request.POST.get('is_active'))
isa.save()
return redirect('engine')
context= {'eng': eng, 'isa': isa}
return render(request, 'base/engine.html', context)
engine.html
{% csrf_token %}
{% for k in isa %}
<label>ON/OFF</label>
<input type="checkbox" id="is_active" name="is_active" {% if
k.is_active == 1 %} checked{% endif %}>
<input type="submit" value="save" />
{% endfor %}
</form>

How to get dynamic html table entries in a form to flask?

I am trying to create a form with an embedded table that the user can dynamically add and remove table rows while entering content into the cell inputs.
HTML
<form id="myForm" action="{{ url_for('hello_world') }}" method="POST">
<div class="form-row text-left">
<div class="col-1 text-left">
<input type="checkbox" id="skills" name="skills" value="Yes">
</div>
<div class = "col-11 text-left">
<h2>TECHNICAL SKILLS</h2>
</div>
</div><!--form-row-->
<div class="form-row">
<table id="myTable" name="skillsTable">
<tr>
<th>Category</th>
<th>Entries</th>
</tr>
</table>
</div><!--form-row-->
<br>
<button type="button" onclick="addSkill()">Add Row</button>
<button type="button" onclick="deleteSkill()">Delete row</button>
<hr>
<input type="submit" value="Submit" onclick="submit()" />
</form>
As you can see in the screenshot [![screenshot of the user form][1]][1] the name attribute is correctly being appended to added cell.
The goal is to have a way to get the table values dynamically created by the user over to the flask template where they can be displayed.
Javascript
<script>
var c1=0;
var c2=0;
function addSkill() {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "<input type='text' value=' ' name=cell1_"+c1.toString()+"> ";
cell2.innerHTML = "<input type='text' value=' ' name=cell2_"+c2.toString()+"> ";
c1++;
c2++;
}
function deleteSkill() {
document.getElementById("myTable").deleteRow(-1);
}
</script>
I have tried setting the name attribute for each newly created cell using a counter, but this still does not show up rendered in the flask template:
flask
#app.route('/hello_world', methods=['GET', 'POST'])
def hello_world():
if request.method == 'POST':
result = {}
try:
skills = request.form['skills']
result['skills'] = skills
result['value'] = request.form['cell1_1']
except:
pass
return render_template("result.html",result = result)
result.html
{% if result.skills %}
<p>{{ result.value }}</p>
{% endif %}
In this example, I would expect to see "Language" show up on rendered after submitting the form if the checkbox is selected.
How can I refer to the table in the form from flask and loop through the <input> elements if they are dynamically created? Thx
[1]: https://i.stack.imgur.com/samhG.png
result.html
{% if result.skills %}
{% set skillsTable = result.skillsTable %}
<h2>TECHNICAL SKILLS</h2>
<table>
{% for skill in skillsTable %}
{% if loop.index|int % 2 == 0 %}
<tr><td>{{ skillsTable.pop(0) }}:</td><td>{{ skillsTable.pop(0) }}</td></tr>
{% else %}
<tr><td>{{ skillsTable.pop(0) }}:</td><td>{{ skillsTable.pop(0) }}</td></tr>
{% endif %}
{% endfor %}
{% endif %}
flask
#app.route('/hello_world', methods=['GET', 'POST'])
def hello_world():
if request.method == 'POST':
result = {}
try:
skills = request.form['skills']
result['skills'] = skills
result['skillsTable'] = []
form = request.form
for key, value in form.items():
if key.startswith("cell"):
result['skillsTable'].append(value)
except:
pass
return render_template("result.html",result = result)

Django - Taking value from POST request

I have a list of zones, identified by id (integer).
How can I get the zone that generated the post request?
manual.html
{% if zone_list %}
<ul>
{% for z in zone_list %}
<b><p>{{z.name}}</p></b>
<form action="" method="post">
{% csrf_token %}
<input type="submit" name="{{z.id}}" value="ON"/>
<input type="submit" name="{{z.id}}" value="OFF"/><br>
<br>
<label>Tiempo</label>:
<input type="integerfield" name="Tiempo">
<input type="submit" name="{{z.id}}" value="Start">
</form>
{% endfor %}
</ul>
{% endif %}
In the views.py I have to change the 1 for something that dynamically represents the zone
views.py
def manual(request):
if request.POST.has_key('1'):
z = Zone.objects.get(id = 1)
keyword = request.POST.get("1","")
if keyword == "ON":
#do something
if keyword == "OFF":
#do something
if keyword == "Start":
#do something
zone_list = Zone.objects.all()
context = {'zone_list':zone_list}
return render(request, 'irrigation_controller/manual.html', context)
I solved the problem. As themanatuf said, I used a hidden input field with the zone_id.
manual.html
{% if zone_list %}
{% for z in zone_list %}
<b><p>{{z.name}}</p></b>
<form action="" method="post">
{% csrf_token %}
<input type="hidden" name="zone_id" value="{{z.id}}">
<input type="submit" name="order" value="ON"/>
<input type="submit" name="order" value="OFF"/><br>
<br>
<label>Tiempo</label>:
<input type="integerfield" name="Tiempo">
<input type="submit" name="order" value="Start">
</form>
{% endfor %}
{% endif %}
And in the view I read the zone_id and the order.
views.py
def manual(request):
if request.POST.has_key('zone_id'):
z = Zone.objects.get(id = request.POST.get("zone_id",""))
keyword = request.POST.get("order","")
if keyword == "ON":
z.irrigation_on()
if keyword == "OFF":
z.irrigation_off()
if keyword == "Start":
tiempo = request.POST['Tiempo']
tiempo = float(tiempo)
irrigation_time.delay(z.id, tiempo)
zone_list = Zone.objects.all()
context = {'zone_list':zone_list}
return render(request, 'irrigation_controller/manual.html', context)

Flask-WTForms: dynamically create name and id attributes

My form allows the user to enter a specific number of names for a specific number of basketball teams. These numbers are constantly updated so I need to create a dynamic form.
Let's say I have the following Flask view:
#app.route('/dynamic', methods=['GET', 'POST'])
def dynamic():
teams = ['Warriors', 'Cavs']
name_count = 2
return render_template('dynamic.html', teams=teams, name_count=name_count)
And the following form in the HTML template dynamic.html:
<form method='POST' action='/dynamic'>
{% for team_index in range(teams | count) %}
{% for name_index in range(name_count) %}
<input type="text"
class="form-control"
id="team{{ team_index }}_name{{ name_index }}"
name="team{{ team_index }}_name{{ name_index }}">
{% endfor %}
{% endfor %}
<form>
Which yields the following form:
<form method='POST' action='/dynamic'>
<input type="text" class="form-control" id="team0_name0" name="team0_name0">
<input type="text" class="form-control" id="team0_name1" name="team0_name1">
<input type="text" class="form-control" id="team1_name0" name="team1_name0">
<input type="text" class="form-control" id="team1_name1" name="team1_name1">
<form>
I love the Flask-WTF library so I'm wondering how I can use that (or simply wtforms) to render this form. I'm not sure this is even possible because wtforms requires a hardcoded field name for every input.
Figured this out. I need to use the WTForms Fieldlist and FormField enclosures.
class PlayerForm(FlaskForm):
player = Fieldlist(StringField('Player'))
class TeamForm(FlaskForm):
team = Fieldlist(FormField(PlayerForm))
#app.route('/dynamic', methods=['GET', 'POST'])
def dynamic():
teams = ['Warriors', 'Cavs']
name_count = 2
# Build dictionary to prepopulate form
prepop_data = {'team': [{'player': ['' for p in range(name_count)]} for team in teams]}
# Initialize form
form = TeamForm(data=prepop_data)
return render_template('dynamic.html', form=form)
And unpacking via jinja2 (id and name attributes on first field = team-0-player-0):
<form method="POST" action="/dynamic">
{{ form.csrf_token }}
{% for team in form.team %}
{{ team.csrf_token }}
{% for player in team.player %}
{{ render_field(player) }}
{% endfor %}
{% endfor %}
</form>

Get POST from multiple dropdowns in one form

Have a form where user can change name on attribut Name and change which attribut a is connected to (attribut b).
Template:
"<form id="form1" name="form1" method="post" action="/define_a/{{c.id}}/edit/">
{% csrf_token %}
{% endblock %}
{% block buttons %}
<p><input type="submit" value="Save" /> Cancel
</p>
{% endblock %}
{% block a_rows %}
{% for a, a_form in a_list %}
<tr><td><img class="icon" src="{{images_dir}}/delete-icon.png"
onclick="javascript: return confirmDelete_name('Are you sure?
This will delete the stuff and all associated information.
The removal happens immediately and cannot be undone.', '{{a.id}}', 'delete');" />
</td><td>{{a_form.name}}</td>
<td>
<select name= "test">
<option value = "Null">None</option>
<option value = "{{a_form.id}}" selected>{{a.b}}</option>
{% for a, a_form in a_list %}
<option value = "{{a_form.id}}">{{a.name}}</option>
{% endfor %}"
View:
Checking that it is a post and that it is valid.
post = [myForm(request.POST, instance = test) for a in a's];
for p in post :
if not new_t.b == p:
if p == 'None':
new_t.b = None;
else:
new_t.b = p;
But i can't get all the values from the dropdown in the post.
I get all a.name in but only one value from the dropdown, sometimes I don't get any value at all.
Any ideas?

Categories

Resources