Why is my checkbox is unchecked after saving? - python

I have created a checkbutton with Python (Django) like this:
in my views.py:
def list(response, list_id):
ls = ToDoList.objects.get(id=list_id)
if response.method == "POST": # If we are POST-ing something (saving, adding items, etc..)
print(response.POST)
if response.POST.get("save"): # SAVING CHECK-BUTTONS
for item in ls.listitem_set.all(): # Loop through all items
if response.POST.get("c" + str(item.id)) == "clicked": # Check if it has been clicked or not
item.complete = True
else:
item.complete = False
item.save()
elif response.POST.get("newItem"): # ADDING ITEM TO LIST
txt = response.POST.get("new") # Get text-input by name
if len(txt) > 2: # Check for valid input
ls.listitem_set.create(text=txt, complete=False)
else:
print("Invalid")
return render(response, "myapp/list.html", {"ls": ls})
and this is my list.html:
{% extends "myapp/base.html" %}
{% block title %}View List of Items{% endblock %}
{% block content %}
<h1>{{ls.name}}</h1>
<form method="POST" action="#">
{% csrf_token %}
<ul>
{% for item in ls.listitem_set.all %}
{% if item.complete == TRUE %}
<li><input type="checkbox" , value="clicked" , name="c{{item.id}}" checked>{{item.text}}</li>
{% else %}
<li><input type="checkbox" , value="clicked" , name="c{{item.id}}">{{item.text}}</li>
{% endif %}
{% endfor %}
</ul>
<button type="submit" , name="save" , value="save">Save</button> <!--Updates checked items -->
<input type="text" , name="new">
<button type="submit" , name="newItem" , value="newItem"> Add Item </button> <!--Adds new items -->
</form>
{% endblock %}
When I open 127.0.0.1:8000/list/1 in my broweser, it displays my 1st list with items and corresponding checkboxes. When I click on a checkbox it gets 'checked' but when I press save and reload, the box is unchecked again. What am I doing wrong here?

Hard to be certain without seeing the page in action, but I would try:
Changing your Django HTML tag if/else condition to 'True' rather than 'TRUE' as I believe in Python it's case sensitive.
Ensure you're ending up in the right path in your if/else statement.

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 implement a next button in flask?

I am trying to use Flask to implement a basic query over a database. Each page should show up to 8 results, and if there are more than 8, it should have a next page button. Everything is working as intended except for the next page button, but I'm not sure what I'm doing wrong.
Here is the Python code I have:
#app.route("/results", methods=["POST"])
def results(result = None):
"""
result page
:return:
"""
query_text = request.form["query"] # Get the raw user query from home page
#~results processing code removed as it's not relevant
hasnext = False
if len(r)>1:
hasnext=True
return render_template("results.html", query=query_text, hits=h , result=r[0], page=1, start = 1, hasnext = hasnext) # add variables as you wish
#app.route("/results/<int:page_id>", methods=["POST"])
def next_page(page_id):
"""
"next page" to show more results
:param page_id:
:return:
"""
s = (page_id-1)*8+1 #numbering of results
next = False
if len(r) >= page_id:
next = True
return render_template("results.html", query=query_text, hits=h, result=r[page_id-1], page=page_id, start = s, hasnext = next)
and then here are the two ways I tried to implement the HTML I have for the button that isn't working:
This one doesn't work (even if I change the variable {{page_id}} to hard code a number)
<a href="{{ url_for('next_page', page_id={{page_id}}+1)}} ">Next
<span class="a-letter-space"></span>
<span class="a-letter-space"></span>
</a>
This one shows the button, and when I tried this code, I also added more to the Python:
Button:
{% if hasnext %}
<form method ="POST" action="/">
<input type="submit" name="Next" value="Next"/>
{% endif %}
</form>
added to Python:
if request.method == 'POST':
if request.form.get('Next') == 'Next':
return render_template("results.html"...)
Any advice on how to implement the next button would be appreciated, thanks!
It's an old post but let me give it a shot. Have you tried to paginate your results? Try this in your python file.
#app.route("/results")
def results():
page = request.args.get('page', 1, type=int)
query_text = Text.query.paginate(page=page,per_page=5)
return render_template('result.html', query_text =query_text)
Then at your results.html insert this code before {% endblock content %} :
{% for page_num in query_text.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2) %}
{% if page_num %}
{% if query_text.page == page_num %}
<a class="btn btn-info mb-4" href="{{ url_for('results', page=page_num) }}">{{ page_num }}</a>
{% else %}
<a class="btn btn-outline-info mb-4" href="{{ url_for('results', page=page_num) }}">{{ page_num }}</a>
{% endif %}
{% else %}
...
{% endif %}
{% endfor %}

Storing variables with sessions django

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']

Django store information in one variable

I have different pages with items, each item has its own price which I would like to store in one variable and then send all of them to paypal payment form.
So question is,how can I store information about price from different pages? I tried sessions but nothing happens.
<article>
{% block content %}
<span>Kuriame mieste registruojiesi</span>
<select>
{% for item in upsell.skaidyti_miestus %}
<option value="{{item}}">{{ item }}</option>
{% endfor %}
</select>
{%if upsell.prideti_upsell_nr_2_taip%}
<button onclick="location.href='/upselliai/{{upsell.upsell_nr2_taip.id}}/pirkti/'">Taip, pridÄ—ti prie bendros sumos</button>
<!-- {#prideti kaina paimti ID} -->
{% else %}
<button onclick="location.href='/pirkejas/apmoketi'">Taip, pridÄ—ti prie bendros sumos</button>
{%endif%}
{%if upsell.prideti_upsell_nr_2_ne%}
{{ upsell.atsisakymo_tekstas }}
<!-- {#prideti kaina paimti ID} -->
{% else %}
{{ upsell.atsisakymo_tekstas }}
{%endif%}
{% endblock %}
</article>
my views.py
def pirkti_upsell(request, upsellis_id = 1):
#if 'pirkejas_id' in request.session:
session_pirkejas_id = request.session['pirkejas_id']
Upsellis.objects.get(id = upsellis_id).sum(session_pirkejas_id)
return render_to_response("upsell_template.html", {"upsell": Upsellis.objects.get(id = upsellis_id)})

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