I have a table with checkboxes and I would like to be able to delete or edit a specific field value for all the selected rows in the table.
Here's an example table that would be awesome to recreate but I have not found examples anywhere how this may work in the view and template. https://examples.bootstrap-table.com/#
My current view, which is working with a table. Where can I start to make the leap from a basic table to an interactive one like in the example above?
Views.py
class EntryList(LoginRequiredMixin, ListView):
context_object_name = 'entry_list'
paginate_by = 100
# paginate_by = 5
#ordering = ['-pk']
model = Entry
template_name = "portfolios/entry_list.html"
def get_queryset(self):
return Entry.objects.filter(created_by=self.request.user).order_by('-pk')
def post(self, request, *args, **kwargs):
ids = self.request.POST.get('ids', "")
# ids if string like "1,2,3,4"
ids = ids.split(",")
try:
# Check ids are valid numbers
ids = map(int, ids)
except ValueError as e:
return JsonResponse(status=400)
# delete items
self.model.objects.filter(id__in=ids).delete()
return JsonResponse({"status": "ok"}, status=204)
entry_list.html
{% extends "dashboard/base.html" %}
{% load i18n %}
{% block content %}
<!-- Page Heading -->
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h2 class="text-gray-800">{% block title %}{% trans "Imported Entries" %}{% endblock %}</h2>
<a role="button" class="btn btn-success" href="{% url 'import' %}"><i
class="fas fa-plus-circle"></i> Import New Entires</a>
</div>
<!-- Content Row -->
<div class="row">
<div class="col-md-12">
<div class="card shadow mb-4">
<div class="card-body">
<div id="dataTable_wrapper" class="dataTables_wrapper dt-bootstrap4">
<div class="row">
</div>
<div class="row">
<div class="col-sm-12">
<table class="table-responsive-xl table table-hover table-striped table-bordered dataTable" id="dataTable" width="100%"
cellspacing="0" role="grid" aria-describedby="dataTable_info">
<thead>
<tr role="row">
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">ID
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Date
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Trade
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Type
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Symbol
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Amount
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Price
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Fee
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Reg Fee
</th>
<th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
colspan="1" aria-label="" style="">Ref
</th>
</tr>
</thead>
<tbody>
{% for entry in object_list %}
<tr role="row">
<td class="text-center">
<div class="custom-control-lg custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input form-control-lg" data-id="{{ entry.pk}}" id="check{{ entry.pk }}">
<label class="custom-control-label" for="check{{ entry.pk }}"></label>
</div>
</td>
<td>{{ entry.pk }}</td>
<td>{{ entry.date | date:"M d, Y h:i:s A"}}</td>
<td>{{ entry.trade.id }}</td>
<td>{{ entry.entry_type }}</td>
<td>{{ entry.symbol }}</td>
<td>{{ entry.amount }}</td>
<td>{{ entry.price }}</td>
<td>{{ entry.fee }}</td>
<td>{{ entry.reg_fee }}</td>
<td>{{ entry.transaction_id }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<!--Pagination-->
<div class="row">
<div class="col-12 ">
<div class="pagination">
<span class="step-links">
{% if page_obj.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
next
last »
{% endif %}
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock content %}
It depends on how you've implemented your frontend, but assuming you have standard django templates, then I would suggest taking a look at datatables. There's quite a lot to it, but it is very stable and has a decent feature set, and the documentation is good. You can style it how you want using bootstrap.
Also, you link to Bootstrap Table - that should be the same principle. Read through the docs to understand how it works, and you will have to use Django template tags to render the data in the table.
Note that the table is implemented using HTML / Jquery, so it is not directly related to Django. All you need to do is to iterate over the django objects in your template (example)
EDIT
How to delete a selected row?
Suppose you could select N rows, and then click a button to delete all of these rows.
This could work as follows:
Add a handler to the delete button:
identify the selected rows
send an Ajax request to delete the rows
handle the success response to remove the deleted rows from the table
// SIMPLIFIED CODE SAMPLE
$("#delete-btn").click(function () {
var selectedRows = table.rows({"selected": true});
var dataObj = {
// parse selectedRows to get object ids
}
$.ajax({
url: '/api/delete-rows/',
type: 'post',
data: dataObj,
success: function (data, status, xhr) {
// remove the selected rows from the view
table.rows({"selected": true}).deselect().remove().draw();
}
})
}
How to select rows and quickly change a field for all of the selected rows?
The same principle here. Once rows are selected, have a handler which identifies the selected rows, then you can use the datatables api to update given fields (docs).
Related
I'm working on a project and I made a form but when I submit sth it doesn't send it to database although in cmd it shows that request method is post.I really don'tkhow how to deal with it.
thats template code:
{%extends 'base.html'%}
{%block title%}
<title>projects</title>
{%endblock title%}
{%block content%}
<div class="container">
</br>
<form method="post">
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" name="project" placeholder="new project?">
</div>
<button type="submit" class="btn btn-primary">add</button>
</form>
</br>
</br>
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col"> project-title</th>
<th scope="col">update</th>
<th scope="col">delete</th>
<th scope="col">divide</th>
</tr>
</thead>
<tbody>
{% for obj in all_projects %}
<tr>
<td>{{ obj.proTitle }}</td>
<td>{{ obj.done }}</td>
<td>Delete</td>
<td>Devide</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{%endblock content%}
any advise will be greatly appreciated:))
I solved it ;
in the input tag i put name="project" but the attribute that I defined in my model was "proTitle"
so when I chnged it the problem solved.
I have a template that contains one search button (this is for filtering the details based on option choose in the select) and a Next button (this is to move to next tab).
When the template loads for then i will search for projects from the select list and the result will be displayed in a table - which is working for me.
After the result is displayed in the table, i will select a row (through radio button) from that table and click on Next button to move to next tab. Here when i click the Next button i want to update some values in the django database but not able to achieve this. Can some one help me?
My View:
def form(request):
projects = CreateProjects.objects.filter(Status=True)
if request.method == 'POST':
selectproject = request.POST.get('selectproject')
searchprojlist = ListProjDetails.objects.filter(Project=selectproject)
return render(request,'form.html',{'projects':projects,'lists': searchprojlist})
elif request.POST.get('tab1btn','') == 'nxttab':
selval = ListProjDetails.objects.get(id=1)
selval.Selected = True
selval.LockedUser = request.user
selval.save()
else:
lists = ListProjDetails.objects.all()
return render(request,'form.html',{'projects':projects})
First If POST is working correctly, trouble is with the 2nd IF (2nd button). I have swapped the 2nd IF to be called fresh after the else statement but not working either.
I have passed id=1 for testing purpose only
enter image description here
I have added the image for better understanding, basically when the template loads select project from the list and Search and then choose one from the output and press next that moves to next tab by updating values like select to True and Locked User to current user.
My view as explained before.
My Javascript:
$(function(){
$('#nexttab').click(function(e){
e.preventDefault();
if(document.getElementById('selectradio').checked){
$('#tabs a[href="#tab2"]').tab('show');
}
});
})
Template:
<form method="POST">
{% csrf_token %}
<div class="row ml-auto">
<select class="custom-select mb-4 ml-2" name="selectproject" style="width: 30em;">
<option selected>Choose...</option>
{% for projects in projects %}
<option>{{ projects.ProjName}}</option>
{% endfor %}
</select>
<div class="ml-4">
<button type="submit" class="btn btn-primary" value="Search">Search</button>
</div>
</div>
<table class="table">
<thead class="thead-light">
<tr>
<th scope="col" class="text-center">S.No.</th>
<th scope="col" class="text-center">Project Name</th>
<th scope="col" class="text-center">Doc</th>
<th scope="col" class="text-center">Target Date</th>
<th scope="col" class="text-center">Docnum</th>
<th scope="col" class="text-center">Type</th>
<th scope="col" class="text-center">Select</th>
<th scope="col" class="text-center">Locked by User</th>
<th scope="col" class="text-center">Status</th>
</tr>
</thead>
<tbody>
{% for lists in lists %}
<tr>
<th scope="row" class="text-center">{{ lists.id }}</th>
<td class="text-center">{{ lists.Project }}</td>
<td class="text-center">{{ lists.doc }}</td>
<td class="text-center">{{ lists.TargetDate }}</td>
<td class="text-center">{{ lists.docnum }}</td>
<td class="text-center">{{ lists.type }}</td>
<td class="text-center"><input class="form-check-input" type="radio"
name="select1" id="selectradio" value="option1"></td>
<td class="text-center">{{ lists.LockedUser }}</td>
<td class="text-center">
{% if lists.DStatus == "Available" %}
<label class="badge badge-success">
{% else %}
<label class="badge badge-warning">
{% endif %}
{{ lists.DStatus }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="text-right mr-5">
<button type="submit" class="btn btn-primary" id="nexttab" name="tab1btn"
value="nxttab">Next</button>
</div>
</form>
I am just trying to re-factor your code, you should be able to pickup then.
from django.shortcuts import render, redirect
from django.urls import reverse
def form(request):
projects = CreateProjects.objects.filter(Status=True)
if request.method == 'POST':
if request.POST.get('tab1btn','') == 'nxttab':
selval = ListProjDetails.objects.get(id=1)
selval.Selected = True
selval.LockedUser = request.user
selval.save()
return redirect(reverse('name-of-the-view')) # redirect to form.html
selectproject = request.POST.get('selectproject')
searchprojlist = ListProjDetails.objects.filter(Project=selectproject)
return render(request,'form.html',{'projects':projects,'lists': searchprojlist})
else:
lists = ListProjDetails.objects.all()
return render(request,'form.html',{'projects':projects})
I've posted the code for a table in django templates that is generated dynamically using an array from views.py. I've added a bootstrap4 collapse, that runs when a chevron button is clicked. However, it shows ALL of the hidden collapses instead of just the collapsible data for that given row (see img below).
I know that I can set ids dynamically, but I haven't had any luck passing functions to the "data-target" attribute.
<table class="table table-hover">
<thead class>
<tr>
<th style="width:5%"></th>
<th>Sample</th>
<th>Reference</th>
<th>Cost</th>
<th>Sum</th>
</tr>
</thead>
<tbody>
<div class="container" id="accordion">
<div class="card">
{% for r in result %}
<tr>
<td>
<button type="button" class="fa fa-chevron-right rotate" data-toggle="collapse"
data-target="#demo" onclick="">
</button>
</td>
<td> {{ r.split.0 }} </td> <!-- sample word -->
<td> {{ r.split.2 }}</td> <!-- ref word -->
<td> {{ r.split.4 }}</td> <!-- cost -->
<td> {{ r.split.3 }}</td> <!-- sum -->
</tr>
<tr>
<td id="demo" class="collapse" colspan="5" >
<!-- COLLAPSE CONTENT -->
</td>
</tr>
{% endfor %}
</div>
</div>
</tbody>
</table>
The "toogle button" have this HTML code:
<button type="button" class="fa fa-chevron-right rotate" data-toggle="collapse"
data-target="#demo">
and the collapsible content is the following:
<td id="demo" class="collapse">[...]</td>
It's normal every toggle button show or hide all collapsible contents in your page, because all these elements are related to the same #demo identifier.
You have to make sure the id of collapsible content is unique accross all the document, and ensure the corresponding button references the same unique id. Maybe use your result id (from context variable) to do something like that:
<button type="button" class="fa fa-chevron-right rotate" data-toggle="collapse"
data-target="#demo-{{ r.pk }}">
<td id="demo-{{ r.pk }}" class="collapse">[...]</td>
EDIT: Of course, you have to adapt it to YOUR data. In this example, I imagine your list result contain many model instances, so in each result r, the value r.pk is unique.
In your template, if results contain something else, you have to make sure a unique str or int is extracted from each value to uniquify the idyou write into your HTML.
Maybe it will be demo-{{ r.split.6 }} or demo-{{ r.a_unique_attr_in_my_object }} or demo-{{ r.slugify }}.
Try to put the content you want to hide under the " COLLAPSE CONTENT ".
like this:
<table class="table table-hover">
<thead class>
<tr>
<th style="width:5%"></th>
<th>Sample</th>
<th>Reference</th>
<th>Cost</th>
<th>Sum</th>
</tr>
</thead>
<tbody>
<div class="container" id="accordion">
<div class="card">
{% for r in result %}
<tr>
<td>
<button type="button" class="fa fa-chevron-right rotate" data-toggle="collapse"
data-target="#demo" onclick="">
</button>
</td>
</tr>
<tr>
<td id="demo" class="collapse" colspan="5" >
<td> {{ r.split.0 }} </td> <!-- sample word -->
<td> {{ r.split.2 }}</td> <!-- ref word -->
<td> {{ r.split.4 }}</td> <!-- cost -->
<td> {{ r.split.3 }}</td> <!-- sum -->
</td>
</tr>
{% endfor %}
</div>
</div>
</tbody>
</table>
By the way, don't forget the Bootstrap CDN
I got 2 queryset list expired_item and queryset in Django ListView, but I don't know when item is expired(queryset is empty), how to display another list expired_item on frond end, no matter what I changed in abc.html, expired_item won't dispaly, I pasted my code as below:
class ABCListView(ListView):
model = ABC
ordering = ('name', 'skill_course')
context_object_name = 'abcs'
template_name = ''
def get_queryset(self, **kwargs):
# Omitted
......
......
# Omitted
expired_item = list(ABC.objects.filter(pk__in=aa).exclude(pk__in=z))
queryset = Permit.objects.filter(pk__in=z)
return queryset
And my html file of abc.html as below:
{% extends 'base.html' %}
{% block content %}
<nav aria-label="breadcrumb">
</nav>
<h2 class="mb-3">My Items list</h2>
<div class="card">
<table class="table mb-0">
<thead>
<tr>
<th>Name</th>
<th>Department</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
{% for a in abcs %}
<tr>
<td class="align-middle">{{ a.name }}</td>
<td class="align-middle">{{ a.department.get_html_badge }}</td>
<td class="align-middle badge badge-pill badge-danger">{{ a.status }}</td>
</tr>
{% empty %}
{% endfor %}
</tbody>
</table>
</div>
<h2 class="mb-3">My Expired Items list</h2>
<div class="card">
<table class="table mb-0">
<thead>
<tr>
<th>Name</th>
<th>Department</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
{% for b in expired_item %}
<tr>
<td class="align-middle">{{ b.name }}</td>
<td class="align-middle">{{ b.department.get_html_badge }}</td>
<td class="align-middle badge badge-pill badge-danger">{{ a.status }}</td>
</tr>
{% empty %}
{% endfor %}
</tbody>
</table>
</div>
<div class="card-footer">
{% endblock %}
Thanks so much for any advice!
I would suggest use a normal django view. This Generic ListView is just created for the use of one list. Just pass both querysets in your context and render your template with that.
You could also use get_context_data() but this would be more or less hacky and not the qay I would recommend.
In my template, i have:
{% with x=0 %}
<div class="wow fadeInUp content-works">
<span class="text-title center" style="color:white">Previous Orders</span>
<div class="card blue-grey darken-1">
<div class="card-content white-text">
<span class="card-title">Order #</span>
<p>${{ payment.}} - {{ user.first_name }} - {{ user.last_name }}</p>
</div>
<div class="card-action">
Link to somewhere
</div>
</div>
</div>
{% endwith %}
Payment.x in this wont output anything (its a filtered database) but when i do payment.0 or payment.1, etc, it shows the data. In the end, i want to put this in a loop so it displays all the data from payment from 0 to the number of values in the filter. Any ideas why this doesnt work?
Fixed - iterated with a for loop:
<div class="wow fadeInUp content-card" style="margin-top: 0;">
<span class="text-title center" style="color:black">Previous Orders</span>
<table class="highlight">
<thead>
<tr>
<th data-field="id">Price</th>
<th data-field="name">Date</th>
<th data-field="price">Name</th>
<th data-field="quantity">Quantity</th>
</tr>
</thead>
<tbody>
{% for payment in b.latest_event_list %}
<tr>
<td>${{payment}}</td>
<td>{{payment.date}}</td>
<td>{{payment.event}}</td>
<td>{{payment.quantity}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
my views:
def dashboard(request):
if request.user.is_anonymous():
messages.add_message(request, messages.ERROR, ' Please Login First before accessing the Dashboard')
return redirect("/student/login")
user = request.user
temp = Payment.objects.filter(user_id=user.id)
tempint = len(temp)
a = Payment.objects.order_by('-id')[:tempint]
a = a[::-1]
b = {'latest_event_list': a}
print a
return render(request, 'student/dashboard.html', {'b': b})
(Put in a table format using materialize to look cleaner)