New to Django/Jquery:
Trying to print "Thanks for signing up!" after a form is submitted.
<script type="text/javascript">
$(function() {
$("input[data-submit-item]").live("click", function() {
var message = "Thanks for signing up!";
$.ajax({
type: "POST",
url: "/add",
data: {
"text": $("#item").val(),
"csrfmiddlewaretoken": $('input[name~="csrfmiddlewaretoken"]').val()
},
success: function(data) {
$("#item-list").append(data);
$("#confmessage").append(message);
$("#item").val("");
}
});
});
});
</script>
</head>
<body>
<div id = "main-container">
<h1>FooBar Baz</h1>
<div id = 'signup-form'>
<form>
<input type="text" id="item" placeholder="Enter your email ..." />
{% csrf_token %}
<div><input type="submit" value="Sign Up" data-submit-item="true" /></div>
</form>
</div>
<div id = "confmessage"></div>
<p><strong>front</strong></p>
<ul id="item-list">
{% for item in line %}
<li>{{ item.text }}</li>
{% endfor %}
</ul>
<p><strong>back</strong></p>
<p>remove</p>
</div>
</div>
</div>
</div>
</body>
</html>
This just prints out a list of all the entered emails but doesnt print the confirmation message. This is a modification of this example: https://github.com/memcachier/memcachier_line/blob/master/templates/index.html
You just need:
$("#confmessage").text(message);
instead of using append.
Related
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.
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 have a from with fields I created in Django models.py. One of the fields is:
res_person_1 = models.TextField(verbose_name="Odgovorna osoba 1")
HTML page is:
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Prijavite nesukladnost</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Prijava</button>
</div>
</form>
</div>
When I inspect the HTML page, ID of object is 'id_res_person_1'. At the page load I run script to get from database all users, which should fill the 'res_person_1' field and that field should be dropdown.
Script is:
<script type="text/javascript">
var endpoint = '/call_jquery_korisnici/'
var korisnik_ime_prezime = []
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
korisnik_ime_prezime = data.korisnik_ime_prezime
console.log(korisnik_ime_prezime)
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
</script>
I don't know how to fill that field and how to make it dropdown. It doesn't work with:
$("#id_res_person_1").html(korisnik_ime_prezime);
document.getElementById('id_res_person_1').value = korisnik_ime_prezime;
If I console output var korisnik_ime_prezime: (2) ["TestName1 TestLastname1", "TestName2 TestLastname1"]
You can use replaceWith to replace your textarea with select-box then use each loop to iterate through your return response from server and then append option inside your select-box.
Demo code :
$(document).ready(function() {
var korisnik_ime_prezime = []
/*$.ajax({
method: "GET",
url: endpoint,
success: function(data) {*/
//just for demo
korisnik_ime_prezime = ["TestName1 TestLastname1", "TestName2 TestLastname1"] // data.korisnik_ime_prezime
//replcae textarea with slect
$("#id_res_person_1").replaceWith("<select name='id_res_person_1' id='id_res_person_1' class='form-control'></select>")
//loop
$(korisnik_ime_prezime).each(function(i) {
$("#id_res_person_1").append("<option>" + korisnik_ime_prezime[i] + "</option>") //append options
})
/*},
error: function(error_data) {
console.log("error")
console.log(error_data)
}
})*/
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<form method="POST" enctype="multipart/form-data">
<textarea id="id_res_person_1"></textarea>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Prijava</button>
</div>
</form>
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 have created a view that generates posts and each post have a comments_set which produces all the comments made by user. When new comment is posted, below function is executed.
$("#comment-post-button").click(function(){
var event_id = document.getElementById('event-id').value;
var url= '/post-comments/'+event_id +'/';
var data = {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
content:document.getElementsByName('comment-post-content')[0].value
}
$.post(url , data, function(){
$("#refresh-comments").load("/comments/" + event_id + '/', function(){
$("#comment-post-content").val("");
});
});
$("#comment-post-content").val("");
return false;
});
The problem is that the page contains multiple posts and each comment submission button has the same id "comment-post-button". So the above function works only for the top post and not for the rest. I can see what the problem is but don't know how to solve this. Please help.
Here is the html markup:
{% for event in events %}
<div class="post">
<div class="post-right">
<div class="post-author">{{ event.author.first_name }}</div>
<div class="post-content">{{ event.description }}</div>
<div class="post-bar">
<div class="post-likes">{{ event.up_votes }}<img src="/site-media/static/images/like.png" /></div>
<div class="post-dislikes">{{ event.down_votes }}<img src="/site-media/static/images/dislike.png" /></div>
<div class="post-timestamp">{{ event.pub_date }}</div>
Comment
</div>
<div class="post-comment">
<form method="post" action="/post-comments/{{ event.id }}/">
{% csrf_token %}
<input type="text" id="comment-post-content" name="comment-post-content" maxlength="200" placeholder="Add a comment..." />
<input type="hidden" id="event-id" value="{{ event.id }}">
<input type="submit" id="comment-post-button" class="comment-post-button" value="Post comment" />
</form>
</div>
<div id="refresh-comments" class="comments">
{% include "comments.html" %}
</div>
</div>
<div class="post-left">
<img src="../FestJanta/site-media/static/images/post.jpg" />
</div>
</div>
{% endfor %}
comments.html:
{% for comment in event.comment_set.all|slice:"3" %}
<div class="comments-right">
{{ comment.author.first_name }}
{{ comment.content }}<br>
<div class="comment-timestamp">{{ comment.pub_date }}</div>
</div>
<div class="comments-left"><img src="../FestJanta/site-media/static/images/comment.jpg" /></div>
{% endfor %}
Final working solution:
$(".comment-post-button").click(function(){
var btn = $(this);
var currentPost = btn.parents('.post');
var event_id = currentPost.find('.event-id').val();
var url= '/post-comments/'+event_id +'/';
var data = {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
content:currentPost.find('input[name="comment-post-content"]').val()
}
$.post(url , data, function(){
$(currentPost.find('.refresh-comments')).load("/comments/" + event_id + '/', function(){
$(currentPost.find('.comment-post-content')).val("");
});
});
return false;
});
Remove id and add class:
<input type="hidden" class="event-id" value="{{ event.id }}">
Do something like this:
$('.comment-post-button').click(function(){
var $btn = $(this);
var $currentPost = $btn.parents('.post');
var event_id = $currentPost.find('.event-id').val();
//...
});
Find each element in $currentPost scope:
Instead of this:
content: document.getElementsByName('comment-post-content')[0].value
Do this:
content: $currentPost.find('input[name="comment-post-content"]').val()
You could do the following:
Identify all post buttons, e.g. by a class like .comment-button
Use the .on() notation of jQuery
Pass the event and use its target property to identify the DOM element that triggered the event
Use traversion to get the correct DOM element of the post
The result should look something like this (untested):
Markup (I basically just got rid of the IDs; not sure how/if django handles this automatically):
{% for event in events %}
<div class="post">
<div class="post-right">
<div class="post-author">{{ event.author.first_name }}</div>
<div class="post-content">{{ event.description }}</div>
<div class="post-bar">
<div class="post-likes">{{ event.up_votes }}<img src="/site-media/static/images/like.png" /></div>
<div class="post-dislikes">{{ event.down_votes }}<img src="/site-media/static/images/dislike.png" /></div>
<div class="post-timestamp">{{ event.pub_date }}</div>
Comment
</div>
<div class="post-comment">
<form method="post" action="/post-comments/{{ event.id }}/">
{% csrf_token %}
<input type="text" name="comment-post-content" maxlength="200" placeholder="Add a comment..." />
<input type="hidden" name="event-id" value="{{ event.id }}">
<input type="submit" class="comment-post-button" value="Post comment" />
</form>
</div>
<div class="comments">
{% include "comments.html" %}
</div>
</div>
<div class="post-left">
<img src="../FestJanta/site-media/static/images/post.jpg" />
</div>
</div>
{% endfor %}
Javascript:
$("body") // Could be any ancestor, body is not the best option
.on('click', '.comment-post-button' function(ev){
var clickTarget = ev.target, // The element clicked on
postElement = $(clickTarget).closest('.post'), // the div enclosing a post
commentSection = $(postElement).find(".comments"), // the div enclosing the comments
commentInputField = $(clickTarget).siblings("[name='comment-post-content']"),
event_id = $(clickTarget).siblings("[name='event-id']").val(),
url= '/post-comments/'+event_id +'/';
// Not sure what this token is, so I will not change that part
var data = {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
content: commentInputField.val()
}
$.post(url , data, function(){
$(commentSection).load("/comments/" + event_id + '/', function(){
$(commentInputField ).val("").prop('disabled', false); // In the callback, empty and reenable
});
});
$(commentInputField ).prop('disabled', true); // I guess disabling the field makes sense
return false;
});
An additional advantage is that you will end up with only one click handler. Note that the solution could be optimized (e.g. by improving the selectors). In addition, jslint will give some warnings.
to give each post & post_Comment_button a unique id, as suggested by someone, change the markup as follows:
{% for event in events %}
<div class="post" id="post_{{forloop.counter}}">
[...]
<input type="submit" id="comment-post-button_{{forloop.counter}}" class="comment-post-button" value="Post comment" />
then change the js function as follows:
$("#comment-post-button").click(function(event){
var buttonNr = event.target.id.replace('comment-post-button_', '');
var postId = 'post_' + buttonNr;
$("#" + postId)... --> and do whatever with it..