Get the values for selected multiple checkbox in Django - python

I am building an app with django. Now i am facing a problem with checkbox. I can retrive the values from request.POST.getlist(checkbox[]). But its comming with a list. Then i am making a for loop to use the slug to get the prices but here i faced like how to store it with a separate variable for each check box. As it is in loop, for different values with different variables is not possibe? How could i do it ?
In my model I have one table with extras. It has SSL, SECURITY, BACKUP.
If the check box of SSL and SECURITY selected then by the slug I will get the price. But i want that to add to Order model which has a fields like SSL and SECURITY .
I am getting totaly confused. How should I make the model architecture. With Hosting user can buy SSL, SECURITY, BACKUP or any of them.
def checkout(request):
if request.method == "POST":
extras_slugs = request.POST.getlist("checkbox[]")
for slug in extras_slugs:

You should use request.POST.getlist here. This is example where I am storing attendance data based on checkbox.
in views:
if request.method == "POST":
id_list = request.POST.getlist('choices')
in html
<form action="{% url 'submitattendance' %}" method="post" role="form">
{% csrf_token %}
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Status</th>
<th><input type="checkbox" align="center" onClick="toggle(this)"></th>
</tr>
</thead>
<tbody>
{% for attendance in attendances %}
<tr {% if attendance.present %} style="background-color:green;"{% endif %}>
<td>{{attendance.first_name}} {{attendance.last_name}}</td>
<td>{{attendance.status}}</td>
<td><input type="checkbox" name="choices" value="{{attendance.id}}" {% if attendance.present %} checked="checked"{% endif %} class="checkbox_delete"></td>
<td><input type="hidden" name="attendances" value="{{attendance.id}}"></td>
</tr>
{% endfor %}
</tbody>
</table>
Hope this helps.

Related

Django: select all data from a row in a html table and use them in a view

I am new to both django and web development.
The task is to run a script when pressin a button using the data contained in the specific row of an html table.
So if i clik on the second button "Run script" it uses all the data in that row (8888, 2020/06/21 06:00) in a separate script to performe some task.
Currently my html file looks like this:
There are 2 sections one for uplading the information that goes in the table one the table which displays them
<h1>Approach Path KML Generator</h1>
<h2>Generate the KML file here:</h2> <form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button onclick="location.href='{% url 'approach_path_receptorsKML:Proejct Creator' %}'">Upload</button> </form>
<h2>Projects Available:</h2>
<table class="table">
<thead>
<tr>
<th>Project ID</th>
<th>Date KML</th>
<th>Time KML</th>
<th>Date-Time Uploaded</th>
<th>Run The Conversion</th>
<th>KML File</th>
</tr>
</thead>
<tbody>
{% for project in latest_project_list %}
<tr>
<td>{{ project.project_ID }}</td>
<td>{{ project.date_kml }}</td>
<td>{{ project.time_kml }}</td>
<td>{{ project.upload_time }}</td>
<td>
<button method="post" value="collect data" name="{{ project.project_ID }}|{{ project.date_kml }}|{{ project.time_kml }}|{{ project.upload_time }}">Run script</button>
</td>
<td>
Download KML File
</td>
</tr>
{% endfor %}
</tbody> </table>
And this is the view I have created:
def ProjectCreator(request):
form = DocumentForm()
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid:
form.save()
elif 'collect data' in request.POST.values():
values = [key for key in request.POST.keys()]
print(values)
else:form = DocumentForm()
I have tried to use this guide (How do I pass table data from a template over to Django on a button/submit click?) however, I have been insuccesfull.
If anyone can spot the mistake I have made and give me some explanation I would be grateful.
Thanks
It doesn't work because you have incorrect HTML layout. Button itself doesn't do anything - in order to send POST request, it should be in <form> tag. Try following:
{% for project in latest_project_list %}
<tr>
<td>{{ project.project_ID }}</td>
<td>{{ project.date_kml }}</td>
<td>{{ project.time_kml }}</td>
<td>{{ project.upload_time }}</td>
<td>
<form method="post">
{% csrf_token %}
<button value="collect data"
name="{{ project.project_ID }}|{{ project.date_kml }}|{{ project.time_kml }}|{{ project.upload_time }}">
Run script
</button>
</form>
</td>
<td>
Download KML File
</td>
</tr>
{% endfor %}
This will work, but I doubt this is great way of achieving this. You can just send project.pk with POST request and fetch project in view. This way you can be sure user will not send incorrect/malicious data with request. It is especially important since your code will run script based on data.

Pass information from html form to python flask

I am new to flask and web applications, trying to create a web application that takes the name and the sport for each user and store it in sqlite DB, now Iam trying to remove users from the DB by taking the registrant id from the html to flask.
flask:
#app.route("/deregister")
def deregister():
value_from_html = ?????
db.excute("DELETE * FROM registrant WHERE id = ?", value_from_html)
html:
{% extends "layout.html" %}
{% block body %}
<h1>Registrant name</h1>
<tbody>
{% for registrant in registrants %}
<tr>
<td>{{ registrant.name }}</td>
<td>{{ registrant.sport }}</td>
<td>
<form action="/deregister" method="post">
<input name="id" type="hidden" value="{{ registrant.id }}"> !-- trying to pass registrant.id to flask --!
<input type="submit" value="Deregister">
</form>
</td>
</tr>
{% endfor %}
</tbody>
{% endblock %}
python code is not complete yet.
You can recieve the form data in the following way.
#app.route("/deregister", methods=['POST'])
#login_required
def deregister():
try:
if request.method == 'POST':
if request.files:
uploaded_file = request.files['filename']
data = uploaded_file.stream.read()
In order to send a variable to flask, you dont need to use forms, you can easily do that in the following way,
#app.route("/deregister/<string:id>", methods=['POST'])
#login_required
def deregister(id):
try:
variable = id
print(variable)
In html, keep this,
{% extends "layout.html" %}
{% block body %}
<h1>Registrant name</h1>
<tbody>
{% for registrant in registrants %}
<tr>
<td>{{ registrant.name }}</td>
<td>{{ registrant.sport }}</td>
<td>
<a href='/deregister/{{ registration.id }}'>Send Id</a>
</td>
</tr>
{% endfor %}
</tbody>
{% endblock %}
After trying to solve it my self finaly Ive found a way to do that:
1)Add button in my html to remove from DB:
I hope that this will help any one as it did for me.

remove from cart using form in template not working in Django

I'm building an Ecommerce App using Django, I'm storing my cart object in Django Sessions, Add to cart, reduce quanity & increase quantity seem to work perfectly on the products page but the same logic isnt working on the cart page. Django isnt throwing any errors. Below is the snippet of code of my form located inside a table on the Cart page & the view function handling its post request:
FORM:
<div class="container">
<div class="border rounded p-4 m-4">
<p class="display-4 pl-4 ml-4">Your Cart</p>
<hr>
<table class="table">
<thead>
<tr>
<th>Sno.</th>
<th>Image</th>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
<th> </th>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td>{{forloop.counter}}</td>
<td>___</td>
<td>{{product.name}}</td>
<td>{{product.price}}</td>
<td>{{product|cart_quantity:request.session.cart}}</td>
<td>{{product|price_total:request.session.cart}}</td>
<td>
<form action="/cart/#{{product.id}}" method="POST">
{% csrf_token %}
<input hidden type="text" name="product" value="{{product.id}}">
<input hidden type="text" name="remove" value="True">
<input type="submit" value=" * " class="btn btn-block btn-light border-right">
</form>
</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<th colspan="4"></th>
<th class="" colspan="">Total</th>
<th>{{products|total_cart_price:request.session.cart}}</th>
</tr>
</tfoot>
</table>
VIEW FUNCTION:
class Cart(View):
def get(self, request):
ids = list(request.session.get('cart').keys())
products = Product.get_products_by_id(ids)
return render(request , 'cart.html' , {'products' : products} )
def post(self, request):
product = request.POST.get('product')
remove = request.POST.get('remove')
cart = request.session.get('cart')
if remove:
cart.pop(product)
else:
pass
return redirect('cart')
Apparently django sessions object needs to be made aware anytime any changes are to be made to the object inside sessions. The fix is to add :
request.session.modified = True
I'm testing this rn and it seems to work fine, what i dont get is why on the homepage it works without adding the modified command. If anyone has any further knowledge on this issue. Do share

Python Django tables with checkbox delete option

I am new to Django and currently trying to display a table with a checkbox which displays the list of records from the database and would have a delete button to delete multiple records using checkbox.
How to display a table with checkbox and delete button?
Appreciate your help!
Here is my code related to it:
models.py
class Customer(TimeStamp):
name = models.CharField(max_length=30, unique=True)
description = models.CharField(max_length=100,blank=True,help_text="Long-form name (optional)")
comments = models.TextField(blank=True)
class Meta:
ordering = ['-id']
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('App_CUS:customer_list')
views.py
class CustomerListView(ListView):
queryset = Customer.objects.order_by('id')
model = Customer
paginate_by = 10
context_object_name = 'customers'
template_name = 'App_CUS/customer_list.html'
customer_list.html
customer_list.html:
{% extends 'index.html' %}
{% load buttons %}
{% block content %}
<div class="pull-right">
{% if perms.App_CUS.customer_add %}
{% add_button 'App_CUS:customer_add' %}
{% delete_button 'App_CUS:customer_delete' %}
{% endif %}
</div>
<h1>{% block title %}Customers{% endblock %}</h1>
<div class="col-md-9">
<div class="table-responsive">
<table class="table table-hover table-headings table-bordered">
<thead>
<tr>
<th class="pk">
<input class="toggle" title="Toggle all" type="checkbox">
</th>
<th>ID</th>
<th>Customer Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{% for customer in customers %}
<tr>
<th class="pk">
<input class="toggle" title="Toggle all" type="checkbox">
</th>
<td>{{ customer.pk }}</td>
<td>{{ customer.name }}</td>
<td>{{ customer.description }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
I would add to your existing
{% for customer in customers %}
a new td tag including something like:
<td>
<div class="checkbox">
<input type="checkbox" name="name_check_{{customer.name}}" id="id_check{{customer.name}}" value="1"
{%if customer.data == 0 %}unchecked {%else%} checked {%endif%}>
</div>
<td>
I've used customer.data to represent a value stored in your db.
You could then write some js to do something on click of each new checkbox.
<script>
$(document).ready(function() {
$("#id_check_{{customer.id}}").on("click", function(){
#do something / ajax call etc..
OR
pass these values back to the view on form post (we've named each checkbox unique to the customer), then process the deletions from there.

Flask Form Only Passing First Item

I am building a cart using Flask for learning purposes. I chose to use SQLite with peewee(ORM) and WTForms. I have it set to display the items from the db with a description and image. I have a form that asks for the quantity then it should add the item and its quantity to the side bar.
The Issue
When You enter a quantity and hit 'add' all the quantity fields will fill with that number and it will post the name of the first item from the database to the sidebar with that quantity.
app.py
#app.route('/cart', methods=['GET', 'POST'])
#login_required
def cart():
form = forms.PartsSelectForm()
if request.method == 'POST':
l_name = Parts.get(Parts.id).part_name
models.List.create(l_part_name=l_name,
l_part_qty=form.quantity.data)
parts = Parts.select()
list = List.select()
return render_template('cart.html', parts=parts, list=list, form=form)
forms.py
class PartsSelectForm(Form):
quantity = IntegerField()
cart.html
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Image</th>
<th>Quantity</th>
<th>Action</th>
</tr>
</thead>
{% for part in parts %}
<tr>
<td>{{ part.part_name }}</td>
<td>{{ part.part_desc }}</td>
<td style="width: 200px; height:200px;"><img src="/static/img/{{ part.part_img }}" style="max-height:100%; max-width:100%"></td>
<form method="POST" action="">
<td>{{ form.quantity }}</td>
<td><button type="submit" id="submit" class="btn btn-success">Add</button></td>
</form>
</tr>
{% endfor %}
</table>
You loop over your parts, but you always use form.quantity, which will be the same on every iteration idependently from which "part" you're currently looping over.

Categories