How can I make actions with selected objects in Django - python

I'm new at Django and have some troubles with making actions with database objects, which I need to select with checkboxes.
models.py
class Scooter (models.Model):
name = models.CharField(max_length=100, verbose_name='name')
price = models.IntegerField(max_length=10, verbose_name='price')
url = models.URLField(verbose_name='url')
views.py
class MainView(TemplateView):
template_name = 'mainApp/index.html'
def get(self, request):
scooters = Scooter.objects.all().order_by('price')
return (render(request, self.template_name, context={'scooters':scooters}))
and my html template is:
<table class="table table-sm table-borderless table-hover table-responsive-lg">
<caption>Перечень товаров</caption>
<thead class="thead-dark">
<tr>
<th scope="col"></th>
<th scope="col">№</th>
<th scope="col">Name</th>
<th scope="col">Price</th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<form action="" method="post">
{% for elem in scooters %}
<tr>
<th>
<input type="checkbox" id="{{ elem.num }}" name="scooter_select" value="/{{ elem.num }}">
<label for="scooter{{ elem.num }}"></label>
</th>
<th>
{{ forloop.counter }}
</th>
<th scope="row">
{{ elem.name }}
</th>
<td>{{ elem.price }}</td>
<td>
Edit
</td>
<td>
Delete
</td>
</tr>
{% endfor %}
</form>
</tbody>
</table>
So I can't understand, how can I catch selected with checkbox objects?

Related

How to pass a variable to a flask app route through a html button

I am trying to create a page where it shows records from the database and shows a delete button next to them. One of the elements shown is the variable needed for the delete function my problem is that I do not know how to get and pass that variable for the route that deletes the record from the database.
routes.py
#app.route("/deletetraining",methods=['GET', 'POST'])
def deleteTraining():
return render_template('deleteTraining.html', trainings = getAllTrainings(), title = 'Delete')
#app.route("/delete")
def delete(tid):
deleteTrainingByID(tid)
return redirect(url_for('deleteTraining'))
deleteTraining.html
{% extends 'layout.html' %}
{% block content %}
<h1 class="text-muted">All Trainings</h1>
<table class="table" >
<thead>
<tr>
<th scope="col">TID</th>
<th scope="col">Workplan</th>
<th scope="col">Cost Centre Code</th>
<th scope="col">Objective</th>
<th scope="col">Name</th>
<th scope="col">Location</th>
<th scope="col">Start Date</th>
<th scope="col">End Date</th>
<th scope="col">Hours</th>
<th scope="col">Days</th>
<th scope="col">Gender Hours</th>
<th scope="col">For MEL</th>
</tr>
</thead>
<tbody>
{% for training in trainings %}
<tr>
{% for element in training %}
<td>{{element}}</td>
{% endfor %}
<td>
<a class="btn btn-danger" type="button" href="/delete">Delete</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock content %}
In the template you must pass the id in the delete training button
<a class="btn btn-danger" type="button" href="/delete/{{training.id}}">Delete</a>
And in your #app.route you must add
#app.route("/delete/<tid>")

django: View to delete html table row not taking effects in Database

I have a page that displays rows from a db table. I added a button to each row that is designed to delete the row upon its click as well as redirect toward a deleted confirmation page. Everything seems to work, unless that nothing gets deleted in the database table.
Here is what my views.py look like:
def ProductsView(request):
queryset = Products.objects.all()
products_list = list(queryset)
request.session['context'] = products_list
#table = ProductsTable(queryset)
#context = {'table':table}
return render(request, 'inventory.html', {'products_list':products_list})
def DeleteProduct(request, Id):
Products.objects.filter(ProductId=Id).delete()
return render(request,'delete_confirmation.html')
and here is what the html page look like, including the code for the delete button
<table class="table text-center table-bordered table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">NAME</th>
<th scope="col">CATEGORY</th>
<th scope="col">TAG NUMBER</th>
<th scope="col">STOCK ON HAND</th>
<th scope="col">DELETE</th>
</tr>
</thead>
<tbody style="background-color: white">
{% for Products in products_list %}
<tr>
<td>{{ Products.ProductId }}</td>
<td>{{ Products.ProductName }}</td>
<td>{{ Products.ProductCategory }}</td>
<td>{{ Products.ProductTagNumber }}</td>
<td>{{ Products.StockOnHand }}</td>
<td>
<a class="btn btn-primary" href="{% url 'delete_confirmation' Id=Products.ProductId %}" style="color: white">Delete</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
here is what urls.py looks like:
path('inventory.html', ProductsView, name="inventory"),
path('delete_confirmation/<int:Id>', DeleteProduct, name="delete_confirmation"),
and when I print Id in console inside of the ``DeleteProduct``` view, it ouputs the correct Id value
I can't find out what I am doing wrong, I have been at it all day and need a pair of fresh eyes to look at it! Does anyone has a clue on what is wrong here?

'post' object is not iterable in django and it is showing error but i'm not getting what's going wrong on code

TypeError at /dashboard
'post' object is not iterable i am just try to get data from db table and show on dashboard in dabel form
my dashboard.html page
{% if posts %}
<table class="table table-dark table-hover">
<thead>
<tr>
<th scope="col" style="width:3%">ID</th>
<th scope="col" style="width:30%">Title</th>
<th scope="col" style="width:55%">Description</th>
<th scope="col" style="width:15%">Action</th>
</tr>
</thead>
<tbody>
{% for post in posts %}
<tr>
<td>{{posts.id}} </td>
<td>{{posts.title}}</td>
<td>{{posts.desc}}</td>
<td><a class="btn btn-primary" type="submit" value="Submit">Edit</a>
<form action ='' , method ='POST' class='d-inline'>
{% csrf_token %}
<input type='submit' class='btn btn-danger btn-sm' value ='Delete' >
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<h4 class =' text-center alert alert-warning'>No Records </h4>
{% endif %}
</div>
</div>
{% endblock content %}
my views.py
def dashboard(request):
if request.user.is_authenticated:
posts= post.objects.all()
return render(request,'dashboard.html',{'posts':post})
else:
return HttpResponseRedirect('login')
urls.py
path('dashboard',views.dashboard,name='dashboard'),
You have a typo in your views.py file. Try change this:
return render(request,'dashboard.html',{'posts':post})
to this:
return render(request,'dashboard.html',{'posts':posts})
I assume in template dashboard.html you have to change this :
{% for post in posts %}
<tr>
<td>{{posts.id}} </td>
<td>{{posts.title}}</td>
<td>{{posts.desc}}</td>
to this :
{% for post in posts %}
<tr>
<td>{{post.id}} </td>
<td>{{post.title}}</td>
<td>{{post.desc}}</td>
It should be like this:
{% for post in posts %}
<tr>
<td>{{post.id}} </td>
<td>{{post.title}}</td>
<td>{{post.desc}}</td>

Too Many Values To Unpack While Rendering Data On A Template (Django)

VIEWS
def Aeging(request):
current_date_thirty = date.today().isoformat()
days_before_thirty = (date.today() - timedelta(days=30)).isoformat()
thirty = journalVoucher.objects.values('account_name_one').order_by('account_name_one').filter(voucher_date_one__range=[days_before_thirty,current_date_thirty]).annotate(outstanding=(Sum('credit_amount_one')-Sum('debit_amount_one')))
for item in thirty:
item['account_name_one'] = CreateLedger.objects.get(id=item['account_name_one'])
return thirty
context ={'thirty':thirty}
return render(request,'report/aeging/aeging_analysis.html',context)
<div class="row">
<div class="table-responsive col-md-6">
<table id="example" class="table table-bordered">
<caption style="caption-side:top; text-align: center;"><h3>0-30 Days</h3></caption>
<thead class="thead-dark">
<tr>
{# <th>S No.</th>#}
<th>Party Name</th>
<th>Total Amount</th>
</tr>
</thead>
<tbody>
{% for item in thirty %}
<tr class="table-success">
{# <td>{{ }} </td>#}
<td>{{item.account_name_one}}</td>
<td>{{ item.outstanding }} </td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr class="totalColumn">
<td style="visibility:hidden;"></td>
<td>Total:</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
Hi The Query Is perfectly Run on python shell but when i render the data on a template it shows too many values to unpack (expected 2).
I Provide You My Views and Template Code.
Any Solution Of This??
Images Link..
https://drive.google.com/drive/folders/1V7uI4YS4Qg8ng4bmN0aCFvp85Dzi8n5S?usp=sharing

Separate the values in dictionary into two column. Python and Django

I've a program which will read data from text file.
There are 3 types of data that I need to read from text file.
visual id
time
tname_pb
Problem
I have 3 columns and need to separate output into different columns.
But, visual id is working perfectly, but time and tname_pb are combined together.
Question
How can I separate time and tname_pb into two different column.
Current views.py based on the picture
with open(path) as input_data:
for line in input_data:
if line.startswith('2_visualid_'):
visual_key = line.lstrip('2_visualid_').rstrip()
data.update({visual_key: []})
if 'time' in tokens:
if search_time in line and visual_key in data:
data[visual_key].append(next(input_data).lstrip('2_mrslt_').rstrip())
if 'tname_pb' in tokens:
if tname_pb in line and visual_key in data:
data[visual_key].append(next(input_data).lstrip('2_mrslt_').rstrip())
Current template based on the picture
<div class="input-group" align="center" style=" left:10px; top:-110px; width:99%">
<table class="table table-bordered">
<thead class="success" >
<tr>
<th class="success">
<b>Visual ID</b>
</th>
<th class="success">
<b>Time Delay Index</b>
</th>
<th class="success">
<b>Tname PB</b>
</th>
</tr>
{% for key, values in output.items %}
<tr class="">
<td rowspan={{ values|length|add:1 }}><b>{{ key }}</b></td>
{% for value in values %}
<tr class="">
<td ><b>{{value}}</b></td>
</tr>
{% endfor %}
</tr>
{% endfor %}
</thead>
</table>
</div>
NOTE
I have tried few examples from Google, but I get errors with them.
I will post them here if they help clarify my question. I left them out because I don't want my question to be confusing.
You have a new table row going on here for each value.
{% for value in values %}
<tr class="">
<td><b>{{value}}</b></td>
</tr>
{% endfor %}
Instead of this, you need to make a new table cell for each value.
<table class="table table-bordered">
<thead class="success">
<tr>
<th class="success">
Visual ID
</th>
<th class="success">
Time Delay Index
</th>
<th class="success">
Tname PB
</th>
</tr>
</thead>
<tbody>
{% for key, values in output.items %}
<tr class="">
<td><b>{{ key }}</b></td>
{% for value in values %}
<td><b>{{ value }}</b></td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>

Categories

Resources