this is html include that add the product and make multi adding random , once it dosnt make duplicate , and once work normally .
{% load i18n %}
{% load static %}
<form >
<div class="tab_content active" data-tab="fruits">
<div class="row ">
{% for productss in my_products %}
<div class="col-lg-3 col-sm-6 d-flex " >
<div class="productset flex-fill" >
<div class="productsetimg">
{% if productss.product_icon %}
<img src="{% url 'productss.product_icon.url' %}" alt="img">
{% else %}
<img src="{% static 'assets/img/product/product1.jpg' %}" alt="img">
{% endif %}
<h6>{% translate "Qty" %}: {{productss.bpq_real_quantity}}</h6>
<div class="">
<i class=""></i>
</div>
</div>
<div class="productsetcontent">
<h4><span id="productee_namee{{productss.id}}">{{productss}}</span></h4>
<h6>{{productss.bpq_product_sell_price}}</h6>
<div class="increment-decrement">
<div class="input-groups">
<input type="button" value="-" onclick="decrementValue{{productss.id}}()" class="button-minus dec button">
<input type="text" name="child" value="1" class="quantity-field" id="plus_field{{productss.id}}" name="quantity_required">
<input type="button" value="+" onclick="incrementValue{{productss.id}}()" class="button-plus inc button" >
<input type="submit" value="{% translate "Add" %}" id="add_item_{{productss.id}}">
</div>
</div>
</div>
</div>
</div>
</form>
<script>
console.log('plus_field{{productss.id}}')
function incrementValue{{productss.id}}()
{
var value = parseInt(document.getElementById('plus_field{{productss.id}}').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('plus_field{{productss.id}}').value = value;
}
function decrementValue{{productss.id}}()
{
var value = parseInt(document.getElementById('plus_field{{productss.id}}').value, 10);
value = isNaN(value) ? 0 : value;
if (value > 1 ) {
value--;
}
document.getElementById('plus_field{{productss.id}}').value = value;
}
</script>
{% comment %} var quantity = $("#quantity_required").val();
$.ajax({
type: "POST",
url: {% url 'view_detail' %},
data: search_word,
success: function(result){
alert("Success");
}
}); {% endcomment %}
{% comment %}
$('#add_item_{{productss.id}}').hide();
setTimeout(function()
{
$('#add_item_{{productss.id}}').show();
}, 1000); {% endcomment %}
{% csrf_token %}
<script>
$(document).ready(function(e){
$(document).on('click','#add_item_{{productss.id}}',function(e){
e.preventDefault();
$('#add_item_{{productss.id}}').attr('disabled', true);
setTimeout(function()
{
$('#add_item_{{productss.id}}').attr('disabled', false);
}, 1000);
var $this = $(this);
var quantity = $("#plus_field{{productss.id}}").val();
var customer = $("#cstname").val();
//console.log(productname);
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
$.ajax({
url:"{% url 'orders:add_item_resturant' productss.pk %}",
type: "POST",
dataType: "json",
data: {
'quantity':quantity,
'customer':customer,
'csrfmiddlewaretoken':csrftoken,
},
success:function(response){
//console.log('success addess')
$('#add_item_update').html(response['result']);
totalprice();
},
});
});
});
</script>
{% endfor %}
</div>
</div>
{% comment %}
<div>
<input id="search" name="search" type="text" class="query-search" placeholder="Search...">
<input onclick="setGetParameter()" type="button" class="btn btn-primary" value = "View Details"/>
</div>
<script>
function setGetParameter(){
var search_word = $("#search").val();
$.ajax({
type: "POST",
url: {% url 'view_detail' %},
data: search_word,
success: function(result){
alert("Success");
}
});
}
</script>
and in views :
def search_view(request):
if request.method == "POST":
search_word = request.POST['data']
{% endcomment %}
this is views.py
def add_item_resturant(request,pk):
print(f"This is request.POST: {request.POST}")
current_user=request.user
customer=Customer.objects.get(customer_name=request.POST['customer'])
CstPoints=customer.customer_Points
user_branch=request.user.user_profile.user_branch
current_order=OrderDetail.objects.select_related('order_order').select_related('order_product_name').filter(order_order__order_progress="In Progress",order_order__order_who_created=current_user)
current_product=BrancheProductQuantity.objects.get(id=pk)
branch_tax=current_product.bpq_branch_name.branch_Tax
real_quantity=current_product.bpq_real_quantity
sell_price=current_product.bpq_product_sell_price
returned_order=Order.objects.get(order_who_created=current_user,order_progress="In Progress")
get_quantity = request.POST['quantity']
if float(real_quantity) - float(get_quantity) < 0 :
messages.warning(request,"Product Quantity is Error and the Quantity of it=" + str(real_quantity) +"and you enter" + get_quantity)
return redirect("orders:add_resturant_order")
if request.method =="POST" :
order_detail , created =OrderDetail.objects.get_or_create(
order_order = returned_order,
order_product_name = current_product)
qfloat=float(get_quantity)
sfloat=float(sell_price)
total_item=float(qfloat*sfloat)
tax=(total_item*branch_tax/100)
price_iclude_tax=tax+total_item
order_detail.order_tax_value=float(tax)
order_detail.order_product_name=current_product
order_detail.order_product_price=current_product.bpq_product_sell_price
order_detail.order_product_quantity=float(get_quantity)
order_detail.order_detail_total=float(total_item)
order_detail.total= float(price_iclude_tax)
order_detail.order_biller_user = str(current_user)
order_detail.order_branch = str(user_branch)
order_detail.save()
final_total_value=current_order.aggregate(Sum('total'))['total__sum']
final_tax_value=current_order.aggregate(Sum('order_tax_value'))['order_tax_value__sum']
full_sub_total=current_order.aggregate(Sum('order_detail_total'))['order_detail_total__sum']
returned_order=returned_order.refresh_from_db()
html = render_to_string('include/add_item_resturant.html',{'CstPoints':CstPoints,'final_total_value':final_total_value,'final_tax_value':final_tax_value,'full_sub_total':full_sub_total,'returned_order':returned_order,'order_detailed':current_order, request:request})
return JsonResponse({'result':html})
enter image description here
I want to solve this problem it make adding product twice and may be 3 or 4 times as showd in page I donst know why is this problem appear.
Related
In Shopify, when cart has item.product_id == 8078327054657, a form will show suggesting to add item.product_id == 8095240388929. However, it doesn't seem to add the item and only checks out when I click the 'Add' button.
I have included the Liquid and HTML codes for the form and the JS codes for the product to be added to cart when button is clicked. It's basically an upsell. Please help me make it work. Thanks
<div class="cart--upsell-es">
{% if cart.item_count > 0 %}
{% for item in cart.items %}
{% if item.product_id == 8078327054657 %}
{% assign in_cart = true %}
{% endif %}
{% endfor %}
{% endif %}
{% if in_cart %}
<div class="cart--upsell-es">
<div style="padding: 20px 0">
<p stye="text-align:center; font-weight:800">Upgrade and Save $41</p>
</div>
<div class="upsell-wrapper">
<form
id="upsell-form"
action="/cart/add"
method="post"
enctype="multipart/form-data">
<input
type="hidden"
name="id"
value="8095240388929" />
<input
type="hidden"
name="quantity"
value="1" />
<img src="https://cdn.shopify.com/s/files/1/0699/3615/2897/files/DTB-BEIGE-min.png?v=1674021338"
width="50px"
height="50px" />
<label for="upsell">Double Trouble Bundle</label>
<button
id="upsell-btn"
type="submit"
value="Add">Add</button>
</form>
</div>
</div>
{% endif %}
</div>
```
```
<script>
if (theme.settings.cart_type === "drawer") {
document.getElementById("upsell-btn").addEventListener("click", function() {
var form = document.querySelector("cart--form");
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/cart/add.js");
xhr.onload = function() {
var item = JSON.parse(xhr.responseText);
var xhr2 = new XMLHttpRequest();
xhr2.open("POST", "/cart/change.js");
xhr2.onload = function() {
var item2 = JSON.parse(xhr2.responseText);
console.log(item2);
};
xhr2.send(JSON.stringify({quantity: 0, id: 8078327054657}));
};
xhr.send(formData);
});
}
</script>
```
I am trying to use a form to submit the parameter to views.py and get the results back to the html. However, the form part was repeatedly display in the page.
enter image description here
Here is my views.py
def fund_main_py(request):
last_trade_date = request.GET['last_trade_date']
print(last_trade_date)
plot_div1, plot_div2 = fund_main_main(last_trade_date)
return render(request, 'optionsfund.html', context={'plot_div1': plot_div1, 'plot_div2': plot_div2})
Here is my stocksettle.js
$(document).ready(function(){
$("#btn_submit").click(function(){
document.getElementById("result").innerHTML = '抓取中.... 若期限過長,請稍後1分鐘!';
var stock_code = $("#stock_code").val();
var last_trade_date = $("#last_trade_date").val();
$.ajax({
type: "GET",
url: "/fund_main_py",
data:{
"stock_code":stock_code,
"last_trade_date":last_trade_date
},
success: function (Data) {
$("#result").html(Data);
},
error: function (e) {
console.log(e);
}
});
})
});
Here is my optionsfund.html
<table border="0">
<tr>
<td><fieldset>
<span> 指數/股票代號 :</span>
<input type="button" id="btn_submit" value=" 查詢 ">
</fieldset></td>
</tr>
</table>
<span id="result">
<span id="plot1">
{% autoescape off %}
{{ plot_div1 }}
{% endautoescape %}
</span><br><br>
<span id="plot2">
{% autoescape off %}
{{ plot_div2 }}
{% endautoescape %}
</span>
</span><br><br>
I am new in ajax as well as Django. I try to put ajax in my code to check that in the signup page if some user is already having one email then that email can't use for new users and disable the button else if the email does not exist then the user can be created.
ajaxCode
$(document).on('blur', 'input[name="email"]', function(){
$.ajax({
type:'POST',
url:'/stock/checkemail/',
data:{
email:$("#email").val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success:function(){
$('input[type="submit"]').attr('disabled', 'true')
},
failure:function(){
$('input[type="submit"]').removeAttr('disabled');
}
})
});
url.py
path('checkemail/',Emailser.as_view()),
views.py
class Emailser(View):
def post(self, request):
em = request.POST['email']
print(em)
try:
user = User.objects.get(email=em)
return HttpResponse('true')
except:
return HttpResponse('false')
In views.py print(em) is also printing mail that type in field but don't know why is not working.
template
{% extends 'base.html' %}
{% block content %}
{% load static %}
<div>
<h2>Sign Up</h2>
{% if error %}
{{error}}
<br/>
{% endif %}
<form method="post" id="signup" >
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary" >Signup</button>
</form>
</div>
<script src="{% static 'assets/signup.js' %}" ></script>
{% endblock %}
try this inside succcess function
$('input[type="submit"]').disabled = true;
$(document).on('blur', 'input[name="email"]', function(){
$.ajax({
type:'POST',
url:'/stock/checkemail/',
data:{
email:$("#email").val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success:function(response){
response ? $('input[type="submit"]').attr('disabled', 'true') : $('input[type="submit"]').removeAttr('disabled');
},
failure:function(error){
console.log(error);
}
})
});
I already did a hashtag in the base.html it is working. like if anyone type something with #something it will replace by the javascript in the html with links. It is working on the post list. so i want to work it on the comments. But the comments have ajax method that's why it is not working in the comments. can we keep them both(AJAX and Hashtag).
my base.html:
$(document).ready(function() {
$("p").each(function(data) {
var strText = $(this).html();
console.log('1. strText=', strText);
var arrElems = strText.match(/#[a-zA-Z0-9]+/g);
console.log('arrElems=', arrElems);
$.each(arrElems, function(index, value){
strText = strText.toString().replace(value, ''+value+'');
});
console.log('2. strText=', strText);
$(this).html(strText);
});
});
(#the ajax method for comments)
$(document).on('submit', '.comment-form', function(event){
event.preventDefault();
console.log($(this).serialize());
$("p").each(function(data) {
var strText = $(this).html();
console.log('1. strText=', strText);
var arrElems = strText.match(/#[a-zA-Z0-9]+/g);
console.log('arrElems=', arrElems);
$.each(arrElems, function(index, value){
strText = strText.toString().replace(value, ''+value+'');
});
console.log('2. strText=', strText);
$(this).html(strText);
});
});
$.ajax({
type: 'POST',
url: $(this).attr('action'),
cache: false,
data: $(this).serialize(),
dataType: 'Json',
success: function(response) {
$('.main-comment-section').html(response['form']);
$('textarea').val('');
$('.reply-btn').click(function() {
$(this).parent().parent().next('.replied-comments').fadeToggle()
$('textarea').val('');
});
},
error: function(rs, e) {
console.log(rs.responseText)
},
});
});
my comments.html:
<form method="post" enctype="multipart/form-data" class="comment-form" action=".">
{% csrf_token %}
{{ comment_form.as_p }}
<input type="submit" value="submit" class="btn-btn-outline-success">
</form>
<div class="container">
{{ comments.count }} comment{{ comments|pluralize }}
{% for comment in comments %}
<blockquote class="blockquote">
<p class="mb-0">{{ comment.content }}</p>
<div class="options">
{% if comment.user == user %}
delete
{% endif %}
</div>
<footer class="blockquote-footer">by <cite title="Source Title">{{ comment.user }}</cite>
<button type="button" name="button" class="reply-btn btn btn-outline-dark btn-sm">reply</button>
</footer>
</blockquote>
<div class="replied-comments container mt-2" style="display:none;">
{% for reply in comment.replies.all %}
<blockquote class="blockquote">
<p class="mb-0"><small>{{ reply.content }}</small></p>
<footer class="blockquote-footer"><small>by <cite title="Source Title">{{ reply.user }}</cite></small></footer>
</blockquote>
{% endfor %}
<div class="form-group-row">
<form method="post" class="reply-form" action="." enctype='multipart/form-data'>
{% csrf_token %}
<input type="hidden" name="comment_id" value="{{ comment.id }}">
{{ comment_form.as_p }}
<input type="submit" value="submit" class="btn-btn-outline-success">
</form>
</div>
</div>
{% endfor %}
the ajax method raise errors like the ajax is not working the hashtag is not working.
well i just have to put the script into the comments.html not in the base.html.
I'm trying to add comment using ajax.
Here is my ajax code:
$(document).ready(function(){
$("#add_comment").click(function(event){
event.preventDefault();
var article_id = {{article.id}};
$.ajax({
url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
type: "get",
success: function(result){
if(result === "validation error"){
alert(result);
}else{
var data = JSON.parse(result);
$("#comment_block").append("<div class = "comment"><span>" + data['owner'] + "</span><p>" + data['comment_text'] + "</p></div>");
}
}
});
});
});
Here is my form of adding comment in django template:
</div>
{% if username %}
<form action="/articles/addcomment/{{ article.id }}/" method="post" id = "comment_form">
{% csrf_token %}
{{ form }}
<input type="submit" class="button" value="Добавить комментарий" id = "add_comment">
</form>
{% endif %}
</div>
Trying to debug, I noticed that it doesn't even step into ajax body. What am I doing wrong then?
I've done ajax query with counting likes and had success in that.
Try this
HTML
</div>
{% if username %}
<form action="#" method="post" id = "comment_form">
{% csrf_token %}
{{ form }}
<input type="text" name = "article" value="{{ article.id }}" id = "article_id">
<input type="text" name = "comment" value="comment goes here" id = "comment_text">
<input type="submit" class="button" value="???????? ???????????" id = "add_comment">
</form>
{% endif %}
</div>
jQuery
$(document).ready(function(){
$("#add_comment").click(function(event){
event.preventDefault();
var article_id = $('#article_id').val();
$.ajax({
url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
type: "POST", /*i belive you are posting data to BE api*/
data:{'comment':"your comment goes here"}, /* use this get what given in input $("#comment_text").val()*/
success: function(result){
/*process data after success call*/
}
});
});
});
Change to the following:
JS Code:
$(document).ready(function(){
$("#comment_form").submit(function(event){
event.preventDefault();
var article_id = $(this).find('.article_id').value();
$.ajax({
url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
type: "post",
success: function(result){
if(result === "validation error"){
alert(result);
}else{
var data = JSON.parse(result);
$("#comment_block").append("<div class = 'comment'><span>" + data['owner'] + "</span><p>" + data['comment_text'] + "</p></div>");
}
}
});
return false;
});
});
Django Template:
</div>
{% if username %}
<form action="/articles/addcomment/{{ article.id }}/" method="post" id = "comment_form">
{% csrf_token %}
{{ form }}
<input type="hidden" class="article_id" value="{{ article.id }}" />
<input type="submit" class="button" value="Добавить комментарий" id = "add_comment">
</form>
{% endif %}
</div>