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
Related
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)
Hey I am quite new to django, I have this function for comments and replies,the problem is I can't have the reply to comments instead it is getting posted as comments. How to have this replies under respective comments? Here is my model and functions.
model
class Comment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
reply = models.ForeignKey('Comment', null=True, related_name='replies', blank=True, on_delete=models.CASCADE)
content = models.TextField(max_length=1000)
timestamp = models.DateTimeField(auto_now_add=True)
views
def comment_section(request, slug):
user = request.user
post = get_object_or_404(Post, slug=slug)
comments = Comment.objects.filter(post=post, reply=None).order_by('-id')
if request.POST:
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
content = request.POST.get('content')
reply_id = request.POST.get('comment_id') #reply-section
comment_qs = None
if reply_id:
comment_qs = Comment.objects.get(id=reply_id)
comment = Comment.objects.create(post=post, user=request.user, content=content, reply=comment_qs)
comment.save()
else:
comment_form = CommentForm()
context = {
'post':post,
'comment_form':comment_form,
'comments': comments,
}
if request.is_ajax():
html = render_to_string('posts/comment_section.html', context, request=request)
return JsonResponse({'form': html})
html
<!-- Comment showing section -->
<div class="main-comment-section">
<div class="container-fluid mt-2">
<div class="form-group row">
<!-- Comment Form -->
<form class="comment-form" method="post" action="{% url 'posts:comment_section' post.slug %}">
{% csrf_token %}
<div class="form-group">
<textarea name="content" cols="60" rows="2" maxlength="1000" required="" id="id_content"></textarea>
</div>
<button type="submit" value="submit" class="btn-sm btn-outline-warning" style="color: black;">Comment</button>
</form>
<!-- Comment Form end -->
</div>
</div>
{% if not post.comment_set.all %}
<small>No comments to display</small>
{% endif %}
{% for comment in post.comment_set.all %}
<blockquote class="blockquote">
<img style="float:left; clear: left;" class="rounded-circle article-img" height="10" width="10" src="{{ comment.user.profile.profile_pic.url }}"><h6>{{ comment.user.first_name|capfirst }} {{ comment.user.last_name|capfirst }}</h6><br>
<p style="font-size: 8px;">{{ comment.timestamp }}</p>
<p style="font-size: 14px;" class="mb-3">{{ comment.content }}</p>
<a type="button" name="button" class="reply-btn ml-4"><i class="fas fa-reply fa-sm"></i></a>
{% if request.user == comment.user %}
<i class="fas fa-trash fa-sm" style="color: brown;"></i></td>
{% endif %}
</blockquote>
{{ comment.reply.count }}
<div class="replied-comments col-md-5" style="display: none;">
{% for reply in comment.replies.all %}
<blockquote class="blockquote">
<img style="float:left; clear: left;" class="rounded-circle article-img" height="50" width="50" src="{{ reply.user.profile.profile_pic.url }}"><h6>{{ reply.user.first_name|capfirst }} {{ reply.user.last_name|capfirst }}</h6><br>
<p style="font-size: 13px;" class="mb-3">{{ reply.content }}</p>
</blockquote>
{% endfor %}
<div class="form-group row">
<form class="reply-form" method="post" action="{% url 'posts:comment_section' post.slug %}">{% csrf_token %}
<input type="hidden" name="comment_id" value="{{ comment.id }}">
<div class="form-group">
<textarea name="content" cols="60" rows="2" maxlength="1000" required="" id="id_content"></textarea>
</div>
<input type="submit" value="submit" class="btn-sm btn-outline-light" style="color: black;">
</form>
</div>
</div>
{% endfor %}
</div>
I guess there is some problem with the form submission, but I can't figure out what it is.
Thanks
This is how I easily solve the problem and it helps me in many ways.
comments = Comment.objects.filter(post=post, reply=None).order_by('-id')
{% for comment in comments %}
{% if comment.reply %}
The IF statement will check if the comment is a reply, this have a parent
If it is, you can access it with {{comment.reply.content}} and {{comment.reply.timestamp}} to print the parent. And {{comment.content}} to print the reply.
{% else %}
I.e. if the comment is just a comment and not a reply.
Just print the comment
{{comment.content}}
{% endfor %}
It is because replies are also comments. You are loading comments in views correctly by :
comments = Comment.objects.filter(post=post, reply=None).order_by('-id')
but in the template you are loading both comments and replies in :
{% for comment in post.comment_set.all %}
try :
{% for comment in comments %}
to load post comments and select replies of each comment by :
{% for reply in comment.replies.all %}
This is my List in the HTML document
I have a Django post view, when I hit send I want the selected users to be posted to the students field.
As you can see I have tried to do the instance and user thing from this url but I can't figure it out!
HTML:
{% for elev in elever %}
<div class="custom-control custom-checkbox">
<span class="d-flex align-items-center">
<div style="margin-right: 10px">
<div class="circle" style="background-color: {{ elev.color }}">
<span class="initials" , style="color: #ffffff"> {{ elev.user|capfirst|first }}
</span>
</div>
</div>
<div style="width: 300px">
<span class="h6 mb-0" data-filter-by="text">{{elev.user|capfirst}}</span>
</div>
<div class="checkboxx"> <input type="checkbox" name="Studyplan-Canview" value= "{{ student.name }}">
<style>
.checkerName {
margin-left: 10px
}
.checkboxx {
align-content: flex-end;
margin-left: 300px
}
</style> </div>
</span>
</label>
</div>
{% endfor %}
The View:
#post request checker
#login_required
def skapa_studieplan(request):
if request.method == 'POST':
name = request.POST.get('Studyplan-Name')
description = request.POST.get('Studyplan-Description')
parent_assignment = Assignment.objects.get(pk=request.POST.get('Studyplan-PAID'))
users = UserProfile.objects.all()
instance = Studyplan.objects.create(request.POST.get('Studyplan-Canview'))
for user in users:
instance.canview.add(user)
studyplan = Studyplan(name=name, description=description, parent_assignment=parent_assignment, canview=instance)
studyplan.save()
return redirect('allaStudieplaner')
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()