I have a list of items. Each item has a checkbox. I want to be able to delete an item using a button that deletes all check item (ones that are ticked). I have some jscript which does half of the work, but removing the item from my database is proving a lot of problems. When I press the the delete button, it removes the item. But when I open up the form again, the item returns again.
Here is my view.
def edit_order(request, order_no):
#some code
items = models.StorageItem.objects.filter(orderservicelist__order__pk = order.pk)
#some more code including if POST
item = models.StorageItem.objects.get(pk = id)
if request.POST.get('delete'):
item.delete()
And my template
{% extends "base_popup.html" %}
{% block title %}
{{title}}
{% endblock %}
{% block script %}
<script type="text/javascript" src="{{MEDIA_URL}}ui/ui.datepicker.min.js"></script>
<script type="text/javascript">
$(function(){
$("#id_required_date").datepicker({dateFormat:"dd/mm/yy"});
$(":checkbox").css("width","auto");
});
$(function(){
$("#check_all").click(function(){
if(this.checked ==true)
$("tbody :checkbox").each(function(){
this.checked=true;
});
else
$("tbody :checkbox").each(function(){
this.checked=false;
});
});
});
</script>
<script>
function hideCheckedRows() {
var checkboxes = document.getElementsByName("item");
var checkboxes_to_remove = new Array();
var count = 0;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked == true) {
checkboxes_to_remove[count++] = checkboxes[i];
}
}
for (var i = 0; i < checkboxes_to_remove.length; i++) {
cbx = checkboxes_to_remove[i];
// parentNode.parentNode.parentNode is the <tr>
// parentNode.parentNode is the <td> containing the checkbox
cbx.parentNode.parentNode.parentNode.removeChild(cbx.parentNode.parentNode);
}
}
</script>
{% endblock %}
{% block content %}
<div id="location_header">{{title}}</div>
<div id="form_container">
<form action="." method="post">
<fieldset class="model">
<p>
<span style="font-weight:bold;font-size:14px">Contact : {{order.contact}}</span>
</p>
<p>
<span style="font-weight:bold;font-size:14px">Cost : {{order.cost}}</span>
</p>
{{ form.as_p }}
</fieldset>
<fieldset class="model">
<legend>Items</legend>
<table id="items_table">
<thead>
<tr>
<td><input type="checkbox" id="check_all" checked="checked"></td>
<td>Tiptop no</td><td>Client no</td><td>Title</td><td>Item type</td>
<td>Format</td>
</tr>
</thead>
<tbody>
{% for item in items %}
<tr>
<td><input type="checkbox" name="item" value="{{item.pk}}" checked="checked"></td>
<td>{{item.tiptop_id}}</td><td>{{item.alternative_id}}</td><td>{{item.title}}</td>
<td>{{item.type}}</td><td>{{item.format}}</td>
</tr>
{% endfor %}
</tbody>
</table>
<p>
<form method="post" action="help">
<table width="60%">
<tr>
<td>
<select name="contact_id">
{% for contact in order.contact.client.contact_set.all %}
<option value="{{contact.pk}}">{{contact}}</option>
{% endfor %}
</select>
</td>
<td>
<select name="status_id">
{% for status in status_list %}
<option value="{{status.pk}}">{{status}}</option>
{% endfor %}
</select>
</td>
<td><input type="submit" name="save_status" value="set status for selected items"></td>
</tr>
</table>
</form>
</p>
</fieldset>
<div id="form_footer">
<span style="font-size:10px;font-weight:bold;margin-right:10px">
</span>
<input type="button" value="Add item" onclick="window.location.href='{% url tiptop.views.client_items name.pk %}'" />
<input type="submit" name="save_item" value="Save" onclick="validate_item(this.form)">
<input type="button" name="delete" value="Delete Items" onclick="hideCheckedRows()">
</div>
</form>
</div>
{% endblock %}
Your problem is that request.POST never contains the delete key.
Those type="button" elements need to be type="submit" to submit the form.
You're just hiding the elements with hideCheckedRows()
Related
I have above html code. Which has table with rows and each row has selection radio button. There is confirm button. I need to send the row data for selected radio option on button click. How should I find what was selected and send that rows data on button click. I want to use javascript but I am very novice in it. Please suggest.
{% extends "base.html" %} {% block title %}Login{% endblock %} {% block content
%}
<html>
<div class="container ">
<h1>You are proposing trade for:: {{desired_item_details[2]}}</h1>
<style>
th, td
{
border:1px solid blue;
padding:10px;
text-align:left;
}
table
{
border-collapse: collapse;
font-size:12px;
text-align: left;
}
</style>
<!-- Content here -->
</div>
<body>
<div class="home">
<br><br><br>
<label>Please Choose Your Proposed Items::</label>
<table>
<tr>
<th>Item#</th>
<th>Game Type</th>
<th>Title</th>
<th>Condition</th>
</tr>
{% for item in proposed_items %}
<tr>
<td>{{item[0]}}</td>
<td>{{item[1]}}</td>
<td>{{item[2]}}</td>
<td>{{item[3]}}</td>
<td>
<input value="{{item[0]}}" id="type_radio_1" name="select" type="radio" /> Select
</td>
</tr>
{% endfor %}
</table>
</div>
<div class="col">
<a class="btn btn-primary btn-lg" role="button">Confirm</a>
</div>
</body>
</html>
{% endblock %}
Here is a simple solution for your question.
document.getElementById("confirmButton").onclick = ( function(event) {
for(var i = 1; i < 4; i++) {
var radioButton = document.getElementById("type_radio_"+i)
if(radioButton.checked){
alert("You have selected" + radioButton.value);
}
}
});
<input value="{{item[0]}}" id="type_radio_1" name="select" type="radio" /><label for="type_radio_1">Select</label>
<input value="{{item[1]}}" id="type_radio_2" name="select" type="radio" /><label for="type_radio_2">Select</label>
<input value="{{item[2]}}" id="type_radio_3" name="select" type="radio" /><label for="type_radio_3">Select</label>
<input type="button" class="btn btn-primary btn-lg" id="confirmButton" value="Confirm">
You can easily do this using a loop and a condition to check whether the current radio button's id in the loop is selected or not. I have changed your confirm button which was a "a" HTML element to a "input" element.
If you want to change the id of the radio input field dynamically, try to use the below code.
document.getElementById("confirmButton").onclick = ( function(event) {
for(var i = 0; i < 3; i++) {
var radioButton = document.getElementById("{{item["+i+"]}}")
if(radioButton.checked){
alert("You have selected" + radioButton.value);
}
}
});
<input value="{{item[0]}}" id="{{item[0]}}" name="select" type="radio" /><label for="{{item[0]}}">Select</label>
<input value="{{item[1]}}" id="{{item[1]}}" name="select" type="radio" /><label for="{{item[1]}}">Select</label>
<input value="{{item[2]}}" id="{{item[2]}}" name="select" type="radio" /><label for="{{item[2]}}">Select</label>
<input type="button" class="btn btn-primary btn-lg" id="confirmButton" value="Confirm">
Thanks and best regards!
I have an issue with my update button and it show this error to me when I click the update button, it is suppose to redirect me to the next page where the staff can update the details, how do I fix that error, so that it can redirect me to the next page where it will show the forms for the staff to update the details
The error I had is shown below here (Traceback error):
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/updatedata/21/
Django Version: 3.1.4
Python Version: 3.8.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'account.apps.AccountConfig',
'crispy_forms',
'channels']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django_session_timeout.middleware.SessionTimeoutMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 186, in _get_response
self.check_response(response, callback)
File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 307, in check_response
raise ValueError(
Exception Type: ValueError at /updatedata/21/
Exception Value: The view account.views.updatedata didn't return an HttpResponse object. It returned None instead.
views.py
#login_required()
def updatedata(request, id):
photo = get_object_or_404(Photo, id=id)
if request.method == 'POST': # check for the post request body
form = UpdateForm(request.POST)
if form.is_valid():
form.save()
return redirect('/logdata')
else:
msg = 'form is not valid' # Show an error message if the form is not valid
else:
form = UpdateForm()
context = {
"form": form,
"photo": photo
}
return render(request, 'updatedata.html', context)
logdata.html
{% extends "home.html" %}
{% block content %}
<style>
table {
border-collapse:separate;
border:solid black 1px;
border-radius:6px;
-moz-border-radius:6px;
}
td, th {
border-left:solid black 1px;
border-top:solid black 1px;
}
th {
border-top: none;
}
td:first-child, th:first-child {
border-left: none;
width: 180px;
}
.pagination a {
padding: 10px;
}
.sort {
display: inline;
margin: 0 20px 0 20px;
}
ul.pagination li a {
display: block;
padding: 5px 15px;
}
ul.pagination li.active {
padding: 5px 15px;
background-color: hsla(199, 34%, 55%, 1);
border-radius: 30px;
color: white;
}
ul.pagination li.disabled {
padding: 5px 15px;
}
ul.pagination li {
display: block;
//border: 1px solid hsla(199, 34%, 64%, 0.74);
}
ul.pagination li a:hover,
ul.pagination li a:active {
border-radius: 30px;
background-color: hsla(199, 34%, 64%, 0.74);
}
#media only screen and (min-width: 268px) {
ul.pagination {
display: flex;
justify-content: left;
align-items: right;
font-size: 18px;
}
</style>
<script>
// Function to download table data into csv file
function download_table_as_csv(table_id, separator = ',') {
var rows = document.querySelectorAll('table#' + table_id + ' tr');
var csv = [];
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll('td, th');
for (var j = 0; j < cols.length; j++) {
var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
data = data.replace(/"/g, '""');
row.push('"' + data + '"');
}
csv.push(row.join(separator));
}
var csv_string = csv.join('\n');
var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
var link = document.createElement('a');
link.style.display = 'none';
link.setAttribute('target', '_blank');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
</script>
<div style="padding-left:16px">
<br>
<div class="form-block">
<h6>Search for Part Number/ Serial Number/ Reception Number/ MCO Number/ Customer Name/ Current Status</h6>
<form class="form-inline my-2 my-lg-0" action="{% url 'logdata' %}" method='GET' value='{{ request.GET.q }}'>
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" name="q" value='{{ request.GET.q }}'/>
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
<div class="sort">
<h5 class="col-md-3">Sort By : </h5>
<div id="sortBlock" class="col-md-9">
<form class="form-inline my-2 my-lg-0" action="" method='GET' value='{{ request.GET.sortType }}'>
<div class="sort">
<input type="radio" id="partno" name="sortType" value="partno">
<label for="partno">Part Number</label>
</div>
<div class="sort">
<input type="radio" id="serialno" name="sortType" value="serialno">
<label for="serialno">Serial Number</label>
</div>
<div class="sort">
<input type="radio" id="mcoNum" name="sortType" value="mcoNum">
<label for="mcoNum">MCO Number</label>
</div>
<div class="sort">
<input type="radio" id="Customername" name="sortType" value="Customername">
<label for="Customername">Customer Name</label>
</div>
<div class="sort">
<input type="Submit" value="Sort"/>
</div>
</form>
</div>
</div>
<br>
<table id="viewTable" class="m-2">
<i class="fa fa-download" aria-hidden="true"></i>
Download as CSV
<br>
<tr class="header">
<th>Latest Log</th>
<th>Part Number</th>
<th>Serial Number</th>
<th>Reception Number</th>
<th>MCO Number</th>
<th>Customer Name</th>
<th>Current Status</th>
<th>Next Status</th>
<th>Action</th>
</tr>
{% for photo in allusername %}
<tr>
<td>{{photo.Datetime}}</td>
<td>{{photo.partno}}</td>
<td>{{photo.serialno}}</td>
<td>{{photo.reception}}</td>
<td>{{photo.mcoNum}}</td>
<td>{{photo.Customername}}</td>
<td>{{photo.status}}</td>
<td>{{photo.nextstatus}}</td>
<td>
<form action="{% url 'logdetails' photo.id %}" method="post">
{% csrf_token %}
<button type="submit" class="btn btn-sm btn-info">View</button>
</form>
</td>
<td>
<form action="{% url 'updatedata' photo.id %}" method="post">
{% csrf_token %}
<button type="submit" name="update_staff_page" class="btn btn-sm btn-info">Update</button>
</form>
{% endfor %}
</table>
<br>
{% if allusername.has_other_pages %}
<ul class="pagination pr-3 mr-1 ml-auto">
{% if allusername.has_previous %}
<li>«</li>
{% else %}
<li class="disabled"><span>«</span></li>
{% endif %}
{% for i in allusername.paginator.page_range %}
{% if allusername.number == i %}
<li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li>{{ i }}</li>
{% endif %}
{% endfor %}
{% if allusername.has_next %}
<li>»</li>
{% else %}
<li class="disabled"><span>»</span></li>
{% endif %}
</ul>
{% endif %}
</div>
</div>
{% endblock %}
forms.py
class UpdateForm(forms.ModelForm):
mcoNum = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "form-control"
}
)
)
reception = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "form-control"
}
)
)
partno = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "form-control"
}
)
)
serialno = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "form-control"
}
)
)
Customername = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "form-control"
}
)
)
class Meta:
model = Photo
fields = ("mcoNum", "reception", "partno", "serialno")
def __init__(self, *args, **kwargs):
super(UpdateForm, self).__init__(*args, **kwargs)
self.fields['mcoNum'].required = False
self.fields['reception'].required = False
self.fields['partno'].required = False
self.fields['serialno'].required = False
updatedata.html
<!doctype html>
{% extends "home.html" %}
{% block content %}
{% load static %}
<html lang="en">
<head>
<style>
.button {
background-color: #38d39f;
border-color: #38d39f;
color: white;
padding: 10px 20px;
text-align: center;
display: inline-block;
margin: 4px 2px;
cursor: pointer;
border-radius: 16px;
width: 275px;
}
</style>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{% static 'fonts/icomoon/style.css' %}">
<link rel="stylesheet" href="{% static 'css/owl.carousel.min.css' %}">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<!-- Style -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
{% if messages %}
{% for message in messages %}
<div class="alert alert-danger" role="alert">
<button type = "button" class="close" data-dismiss = "alert">x</button>
{{ message }}
</div>
{% endfor %}
{% endif %}
<div style="padding-left:16px">
<table class="first" cellspacing="0" cellpadding="0">
<tr>
<h5>Current Log Data</h5>
</tr>
<br>
<tr>
<th>MCO Number: {{photo.mcoNum}}</th>
</tr>
<tr>
<th>Reception Number: {{photo.reception}}</th>
</tr>
<tr>
<th>Part Number: {{photo.partno}}</th>
</tr>
<tr>
<th>Serial Number: {{photo.serialno}}</th>
</tr>
<tr>
<th>Customer Name: {{photo.Customername}}</th>
</tr>
</table>
<div class="content">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6 contents">
<div class="row justify-content-center">
<div class="col-md-25">
Go Back
<div class="form-block">
<div class="mb-3">
</div>
<h2>Update Log Data</h2>
<br/>
<form method="post">
{% csrf_token %}
<br>
<div class="form-group first">
<label for="MCO">MCO Number</label>
{{ form.mcoNum }}
</div>
<br>
<div class="form-group last mb-4">
<label for="Reception">Reception Number</label>
{{ form.reception }}
</div>
<br>
<div class="form-group last mb-4">
<label for="partno">Part Number</label>
{{ form.partno }}
</div>
<br>
<div class="form-group last mb-4">
<label for="serialno">Serial Number</label>
{{ form.serialno }}
</div>
<br>
<div class="form-group last mb-4">
<label for="Customername">Customer Name</label>
{{ form.Customername }}
</div>
<button class="button" >Submit</button>
<br>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="{% static 'js/jquery-3.3.1.min.js' %}"></script>
<script src="{% static 'js/popper.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
<script src="{% static 'js/main.js' %}"></script>
</div>
{% endblock %}
change your view into this
views.py
from django.http import Http404
from django.contrib import messages
#login_required()
def updatedata(request, id):
try:
photo = Photo.objects.get(id=id)
if request.method == 'POST' and 'update_staff' not in request.POST: # check for the post request body
form = UpdateForm(request.POST)
if form.is_valid():
form.save()
return redirect('/logdata')
else:
messages.add_message(request, messages.ERROR, 'form is not valid') # Show an error message if the form is not valid
else:
form = UpdateForm(instance=photo)
context = {
"form": form,
"photo": photo
}
return render(request, 'updatedata.html', context)
except Exception as e:
raise Http404
and your template into this
logdata.html
<form action="{% url 'updatedata' photo.id %}" method="post">
{% csrf_token %}
<button type="submit" name="update_staff_page" class="btn btn-sm btn-info">Update</button>
</form>
i think you not make clear statement, if the post don't send any data on method post you submit
I have a web page as shown below, so when I click on any 1 of my radio button, my url will show what I have click but, my data table won't sort in ascending order according to what I have selected, how do I fix this issue and how do I make it so that when I use the search bar and filter the page, it will still be sort in ascending order?
views.py
#login_required()
def ViewMCO(request):
search_post = request.GET.get('q')
if (search_post is not None) and search_post:
allusername = Photo.objects.filter(Q(reception__icontains=search_post) | Q(partno__icontains=search_post) | Q(
Customername__icontains=search_post) | Q(mcoNum__icontains=search_post) | Q(status__icontains=search_post)
| Q(serialno__icontains=search_post))
if not allusername:
allusername = Photo.objects.all().order_by("-Datetime")
else:
allusername = Photo.objects.all().order_by("-Datetime") # The newest submitted log data will appear at the top
page = request.GET.get('page')
paginator = Paginator(allusername, 6)
try:
allusername = paginator.page(page)
except PageNotAnInteger:
allusername = paginator.page(1)
except EmptyPage:
allusername = paginator.page(paginator.num_pages)
context = {'allusername': allusername, 'query': search_post}
return render(request, 'ViewMCO.html', context)
ViewMCO.html
{% extends "customerbase.html" %}
{% block content %}
<style>
table {
border-collapse:separate;
border:solid black 1px;
border-radius:6px;
-moz-border-radius:6px;
}
td, th {
border-left:solid black 1px;
border-top:solid black 1px;
}
th {
border-top: none;
}
td:first-child, th:first-child {
border-left: none;
}
.pagination a {
padding: 10px;
}
.sort {
display: inline;
margin: 0 20px 0 20px;
}
</style>
<script>
// Function to download table data into csv file
function download_table_as_csv(table_id, separator = ',') {
var rows = document.querySelectorAll('table#' + table_id + ' tr');
var csv = [];
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll('td, th');
for (var j = 0; j < cols.length; j++) {
var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
data = data.replace(/"/g, '""');
row.push('"' + data + '"');
}
csv.push(row.join(separator));
}
var csv_string = csv.join('\n');
var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
var link = document.createElement('a');
link.style.display = 'none';
link.setAttribute('target', '_blank');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
</script>
<div style="padding-left:16px">
<br>
<div class="form-block">
<h6>Search for Part Number/ Serial Number/ Reception Number/ MCO Number/ Customer Name/ Status</h6>
<form class="form-inline my-2 my-lg-0" action="{% url 'ViewMCO' %}" method='GET' value='{{ request.GET.q }}'>
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" name="q" value='{{ request.GET.q }}'/>
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
<div class="sort">
<h5 class="col-md-3">Sort By : </h5>
<div id="sortBlock" class="col-md-9">
<form class="form-inline my-2 my-lg-0" action="{% url 'ViewMCO' %}" method='GET' value='{{ request.GET.p }}'>
<div class="sort">
<input type="radio" id="partno" name="sortType" value="partno">
<label for="partno">Part Number</label>
</div>
<div class="sort">
<input type="radio" id="serialno" name="sortType" value="serialno">
<label for="serialno">Serial Number</label>
</div>
<div class="sort">
<input type="radio" id="receptionno" name="sortType" value="receptionno">
<label for="receptionno">Reception Number</label>
</div>
<div class="sort">
<input type="radio" id="mcoNum" name="sortType" value="mcoNum">
<label for="mcoNum">MCO Number</label>
</div>
<div class="sort">
<input type="radio" id="Customername" name="sortType" value="Customername">
<label for="Customername">Customer Name</label>
</div>
<div class="sort">
<input type="Submit" value="Sort"/>
</div>
</form>
</div>
</div>
</div>
<table id="viewTable" class="m-2">
<i class="fa fa-download" aria-hidden="true"></i>
Download as CSV
<br>
<tr class="header">
<th>Latest Log</th>
<th>Part Number</th>
<th>Serial Number</th>
<th>Reception Number</th>
<th>MCO Number</th>
<th>Customer Name</th>
<th>Status</th>
<th>Action</th>
</tr>
{% for photo in allusername %}
<tr>
<td>{{photo.Datetime}}</td>
<td>{{photo.partno}}</td>
<td>{{photo.serialno}}</td>
<td>{{photo.reception}}</td>
<td>{{photo.mcoNum}}</td>
<td>{{photo.Customername}}</td>
<td>{{photo.status}}</td>
<td>
<form action="{% url 'customerdetails' photo.id %}" method="post">
{% csrf_token %}
<button type="submit" class="btn btn-sm btn-info">View</button>
</form>
</td>
</tr>
{% endfor %}
</table>
<br>
{% if allusername.has_other_pages %}
<ul class="pagination pr-3 mr-1 ml-auto">
{% if allusername.has_previous %}
<li>«</li>
{% else %}
<li class="disabled"><span>«</span></li>
{% endif %}
{% for i in allusername.paginator.page_range %}
{% if allusername.number == i %}
<li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li>{{ i }}</li>
{% endif %}
{% endfor %}
{% if allusername.has_next %}
<li>»</li>
{% else %}
<li class="disabled"><span>»</span></li>
{% endif %}
</ul>
{% endif %}
</div>
{% endblock %}
If you want to sort the queryset data, it needs to be implemented like below. If you want to add descending or ascending sort_by, then you can make it with passing order_by parameter with '-' as descending, empty string as ascending, for example '-id' as descending, 'id' as ascending.
#login_required()
def ViewMCO(request):
search_post = request.GET.get('q')
if (search_post is not None) and search_post:
allusername = Photo.objects.filter(Q(reception__icontains=search_post) | Q(partno__icontains=search_post) | Q(
Customername__icontains=search_post) | Q(mcoNum__icontains=search_post) | Q(status__icontains=search_post)
| Q(serialno__icontains=search_post))
if not allusername:
allusername = Photo.objects.all().order_by("-Datetime")
else:
allusername = Photo.objects.all().order_by("-Datetime") # The newest submitted log data will appear at the top
# example code starts
sort_type = request.GET.get('sortType')
allusername = allusername.order_by(sort_type)
# example code ends
page = request.GET.get('page')
paginator = Paginator(allusername, 6)
try:
allusername = paginator.page(page)
except PageNotAnInteger:
allusername = paginator.page(1)
except EmptyPage:
allusername = paginator.page(paginator.num_pages)
context = {'allusername': allusername, 'query': search_post}
return render(request, 'ViewMCO.html', context)
I have following products in the database:
Html code for the above image:
{% for crops_ordered_names,crops_ordered_images,crops_ordered_cost,crops_ava in total %}
<tbody>
<tr>
<td data-th="Product">
<div class="row">
<div class="col-sm-2 hidden-xs"><img alt="..." class="img-responsive" src="http://placehold.it/100x100"/>
</div>
<div class="col-sm-10">
<h4 class="nomargin">{{crops_ordered_names}}</h4>
<p>Available amount: {{crops_ava}}</p>
</div>
</div>
</td>
<td data-th="Price" data-type="price">{{crops_ordered_cost}}</td>
<td data-th="Quantity">
<input class="form-control text-center" data-type="quan" max="{{crops_ava}}" min="1" type="number">
</td>
<td class="text-center" data-th="Subtotal" data-type="subtotal"></td>
<td class="actions" data-th="">
<a href="{% url 'shopping_cart:delete_item' crops_ordered_names%}">
<button class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>
</a>
</td>
</tr>
</tbody>
How can I send the value quantity of each item to the django views to store quantity of each item to the respective product when I submit the form after entering all the quantities.
I need to get value of quantity from the HTML code:
<input type="number" class="form-control text-center" data-type="quan" min="1" max="{{crops_ava}}" >
I was working on something similar. And I've used ajax to update the quantity. I'm not very good at explaining things, but I tried.
Get the quantity of the unique item using id="quantity{{item.id}}
<div style="flex:1">
<p id="quantity{{ item.id }}" class="align-content-center quantity">{{ item.quantity }}</p>
<div class="quantity_btns">
<img height="15" width="15" class="chg-quantity update_cart" data-product="{{ item.id }}" data-action="add" src="{% static 'images/arrow-up.png' %}">
<img height="15" width="15" class="chg-quantity update_cart" data-product="{{ item.id }}" data-action="remove" src="{% static 'images/arrow-down.png' %}">
</div>
</div>
And below is the ajax code.
let update_cart = document.getElementsByClassName('update_cart');
for (var i = 0; i < update_cart.length; i++) {
update_cart[i].addEventListener('click', function() {
var data_action = $(this).data('action');
var product_id = $(this).data('product');
let quantity = document.getElementById('quantity' + product_id);
$.ajax({
url:'/test_add_cart_button',
data:{
'data_action':data_action,
'product_id':product_id,
},
success: function(data){
quantity.innerHTML = data.item_quantity;
}
});
});
}
Little summary of above code. We get all the elements with class "update_cart". Loop through all the elements. Get the attribute value of data-action which contains add/remove action. Then get the attribute data-product(which contains the {{ item.id }}). Get the quantity of the product the using getElementById('quantity' + product_id). Where the product_id will be retrieved from the data-product.
Then in the ajax, we send the value we captured in a key to send it to our view.
def test_add_cart_button(request):
clicked = request.GET.get('data_action')
product_id = request.GET.get('product_id')
item = CartItem.objects.get(id=product_id, user=request.user)
if clicked == 'add':
item.quantity += 1
item.save()
elif clicked == 'remove':
item.quantity -= 1
if item.quantity <= 0:
remove_from_cart(request, item.id)
return JsonResponse({'item_quantity':item.quantity,}, safe=False)
With data_action and product_id keys. We can use them in our view by request.GET.get('data_action') and request.GET.get('product').
its quite similar my projects. I think this code help you
models.py
class OrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
ordered = models.BooleanField(default=False)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
def __str__(self):
return f"{self.item.product_title} No. of quantity : {self.quantity}"
def get_total_item_price(self):
return self.quantity * self.item.product_price
def get_total_discount_item_price(self):
return self.quantity * self.item.product_discount_price
def get_amount_saved(self):
return self.get_total_item_price() - self.get_total_discount_item_price()
def get_final_price(self):
if self.item.product_discount_price:
return self.get_total_discount_item_price()
return self.get_total_item_price()
views.py
class Cartview(LoginRequiredMixin, View):
def get(self, *args, **kwargs):
try:
order = Order.objects.get(user=self.request.user, ordered=False)
context = {
'object': order
}
return render(self.request, 'cart.html', context)
except ObjectDoesNotExist:
messages.warning(self.request, "You do not have an active order")
return redirect("/")
Jinja template with for looping
<tbody>
{% for order_item in object.items.all %}
<tr class="text-center">
<td class="product-remove"><span style=color:burlywood; class="badge badge-light">{{forloop.counter}}</span></td>
<td class="image-prod">
<div class="img" style="background-image:url({{order_item.item.product_image.url}});"></div>
</td>
<td class="product-name">
<h3>{{order_item.item.product_title}}</h3>
<p>{{order_item.item.product_description}}</p>
</td>
<td class="price">
{% if order_item.item.product_offer %}
<span class="ml-2 price-sale">₹ {{order_item.item.product_discount_price}}</span> {% else %}
<span class="price-sale">₹ {{order_item.item.product_price}}</span> {% endif %}
</td>
<td class="quantity">
<div class="input-group mb-3">
-
<input type="text" name="quantity" class="quantity form-control input-number" value="{{ order_item.quantity }}">
+
</div>
</td>
<td class=" total ">
{% if order_item.item.product_offer %} ₹ {{ order_item.get_total_discount_item_price }}
<span class="badge badge-info">Saving ₹ {{ order_item.get_amount_saved }}</span> {% else %} ₹{{ order_item.get_total_item_price }} {% endif %}
</td>
<td class="product-remove"><span class="ion-ios-close"></span></td>
{% empty %}
<tr>
<td colspan='6'>Your cart is empty</td>
</tr>
</tr>
{% endfor %}
<!-- END TR-->
</tbody>
</table>
</div>
</div>
</div>
<div class="row justify-content-start ">
<div class="col col-lg-5 col-md-6 mt-5 cart-wrap ftco-animate ">
{% if object.get_total %}
<div class="cart-total mb-3 ">
<h3>Cart Totals</h3>
<p class="d-flex ">
<span>Subtotal</span>
<span>{{object.get_total}}</span>
</p>
<p class="d-flex ">
<span>Delivery</span>
<span>0.00</span>
</p>
<p class="d-flex ">
<span>Discount</span>
<span>0.00</span>
</p>
<hr>
<p class="d-flex total-price ">
<span>Total</span>
<span> ₹ {{object.get_total}}</span>
</p>
</div>
{% endif %}
follow this Django build-in functions documents
Good Day!
I'm having a unique problem where I have to create a HTML page which has 3 forms, in which the radio buttons are generated dynamically based on the input of the previous form. I'm using Python 3.6 and HTML.
Parts of my code:
from the app:
selection1 = sorted(list(Some_Table['var1'].unique()))
if request.method == 'POST':
if request.form['submit1']:
selection2 = sorted(list(pandas.DataFrame(Some_Table[Some_Table['var1'] == request.form['Header1']])['var2'].unique()))
return render_template('view.html', selection2 = selection2, selection1=selection1)
if request.form['submit2']:
selection3 = sorted(list(pandas.DataFrame(Some_Table[Some_Table['var2'] == request.form['Header2']])['var3'].unique()))
return render_template('view.html', selection3 = selection3, selection2 = selection2, selection1=selection1)
return render_template('view.html', selection1=selection1)
from the html script:
<div2>
<form action="" method="post">
<p> {% for c1 in selection1 %}
<input type="radio" name="Header1" value={{c1}}> {{c1}} </input><br>
{% endfor %} </p>
<p> <input type=submit name=submit1 value="Show Table1"> </p>
</form>
</div2>
<div2 style="margin-top: 250px; ">
<form action="" method="post">
<p> {% for c2 in selection2 %}
<input type="radio" name="Header2" value={{c2}}> {{c2}} </input><br>
{% endfor %} </p>
<p> <input type=submit name=submit2 value="Show Table2"> </p>
</form>
</div2>
<div2 style="margin-top: 500px; ">
<form action="" method="post">
<p> {% for c3 in selection3 %}
<input type="radio" name="Header3" value={{c3}}> {{c3}} </input><br>
{% endfor %} </p>
<p> <input type=submit name=submit3 value="Show Table3"> </p>
</form>
</div2>
JAVASCRIPT
for (i = 0; i < 20; i++) {
var radioBtn = $('<input type="radio" name="rbtnCount" />');
radioBtn.appendTo('#target');
}
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="target"></form>