Ajax returning `none` in django - python

I Have this form in a table with two button.
Code:
index.html
<form action="{% url 'Prediction' %}" method="post">
{% csrf_token %}
<table class="table table-striped table-dark" cellspacing="0">
<thead class="bg-info">
<tr>
<th>Company's Symbol</th>
<th>Current Price</th>
<th>View Current chart</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for a,b in stocks %}
<tr>
<th scope="row" class="comp_name">{{ a }}</th>
<td>{{ b }}</td>
<td>
<input type="submit" class="btn graph-btn" formaction="{% url 'Graph' %}" name="_graph" value="View Graph">
</td>
<td>
<input type="submit" class="btn predict-btn" name="_predict" value="Predict Closing Price">
</td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
By clicking .graph-btn I need to pass the data of row that button is clicked on. Here is code that's working.
<script>
$(".graph-btn").click(function() {
var $row = $(this).closest("tr");
var $text = $row.find(".comp_name").text();
console.log($text);
$.ajax({
type:'POST',
url:'{% url 'Graph' %}',
data:{
text: $text,
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
},
success:function(json){
console.log($text);
},
error : function(xhr,errmsg,err) {
}
});
});
</script>
But Problem is that In views.py returning none:
views.py
def graph(request):
if request.method == 'POST' and '_graph' in request.POST:
print(request.POST.get('text'))
# context = {'name': name}
# # print(name)
return render(request, 'StockPrediction/chart.html')
else:
return render(request, 'StockPrediction/greet.html')
urls.py
urlpatterns = [
path("", views.greet, name='greet'),
path("index/", views.index, name='Stock Prediction'),
path("prediction/", views.prediction, name='Prediction'),
path("view/", views.graph, name='Graph'),
]

try adding dataType: 'json' to the request. For example:
$.ajax({
type: 'post',
url: '{% url 'Graph' %}',
headers: {
'X-CSRFToken': $('input[name=csrfmiddlewaretoken]').val()
}
data: {
text: $text,
},
dataType: 'json',
success: function (data) {
console.log(data)
},
error: function(error) {
console.log(error)
}
});

In your views function graph(request) you are not returning a value but instead rendering an HTML page with the request.
A view function in Django should either return a JSON or a dictionary or can return a Webpage You can either do one of following
1) return a dictionary or JSON
return {"key":"value","key":"value"}
2) return a HttpResponse
return HttpResponse(status_code, response_data)
3) Redirect to another page
return redirect('/some/redirect/url/')
Try the above and comment if it helps

Related

How to use a drop down and pagination without getting values reset while going back and forth through pages in DJANGO?

I have a form with a drop down to search. Drop down values help to search for a specific hostname (A field value in elasticsearch).
When I go back and forth through pages while using the default dropdown value I don't get any error. But, When I am on page 2/5 (for default dropdown value) and then search for a new hostname my url returns http://localhost:8000/?page=2 and the new hostname in my views.py which is not what I want.
In my Views.py if the request if GET (while using the Default hostname value / no form submission) my code goes to the else statement and when I search it goes to the IF statement (POST request with parameters)
VIEWS.PY
def check(request):
if request.method == 'POST':
host = request.POST['host']
rows = []
query = {
"sort": {"#timestamp": {"order": "desc"}},
"size" : 10,
"_source": ["data.service","data.policyid","data.srcuser"],
"query":{
"bool": {
"must": [
{"match_phrase": {"data.action": "deny"}},
{"match_phrase": {"data.devname": host}}
]
}
}
}
index_name = "mssp-stl.archives-2022.04.13"
rel = es.search(index=index_name, body= query)
data = rel['hits']['hits']
for i in data:
row = {
'policyid' : i['_source']['data']['policyid'],
'service' : i['_source']['data']['service']
}
rows.append(row)
data = pd.DataFrame(rows)
p = Paginator(rows, 2)
page = request.GET.get('page')
venues = p.get_page(page)
return render(request, 'firewall_analyser/test.html',
{
'rows': rows,
'venues': venues,
'hosts':names,
'host': host
}
)
else:
rows = []
query = {
"size" : 10,
"sort": {"#timestamp": {"order": "desc"}},
"_source": ["data.service","data.policyid","data.srcuser"],
"query":{
"bool": {
"must": [
{"match_phrase": {"data.action": "deny"}},
{"match_phrase": {"data.devname": "FGT100E-MUMDC-Secondary"}}
]
}
}
}
index_name = "mssp-stl.archives-2022.04.13"
rel = es.search(index=index_name, body= query)
data = rel['hits']['hits']
for i in data:
row = {
'policyid' : i['_source']['data']['policyid'],
'service' : i['_source']['data']['service']
}
rows.append(row)
data = pd.DataFrame(rows)
p = Paginator(rows, 2)
page = request.GET.get('page')
venues = p.get_page(page)
return render(request, 'firewall_analyser/test.html',
{
'rows': rows,
'venues': venues,
'hosts':names,
'host': "FGT100E-MUMDC-Secondary"
}
)
When I go to the nextpage or previous page my code always goes to the else statement (GET method) where the hostname is hardcoded value and all my results in table are wrong.
pagination.html
<script>
window.onload = function exampleFunction() {
var host = '{{host}}'
if (host){
$("#host").val(host).change();
}
}
</script>
<body>
<form method="POST" class="form-inline" id ='post-form' action="">
{% csrf_token %}
<div class="form-group">
<label class="form-check-label"><b style="color: #141313;">Host </b></label>
<select name="host" id="host">
{% for i in hosts %}
<option value={{i}}>{{i}}</option>
{% endfor%}
</select>
</div>
<div class="form-group">
<label class="form-check-label"> </label>
<button type="submit" class="btn styled btn-Fetch"><b>Search</b></button>
</div>
</form>
<table>
<th>idno</th>
<th>Policy ID</th>
<th>Service</th>
{% for i in venues %}
<tr>
<td>{{ forloop.counter }}</td>
<td> {{i.policyid}}</td>
<td>{{i.service}}</td>
</tr>
{% endfor %}
</table>
<hr> <br/><br/>
{{venues}} <br/>
Has Previous : {{venues.has_previous}} <br/>
Has Next : {{venues.has_next}}<br/>
Current Page : {{venues.number}}<br/>
Number of pages : {{venues.paginator.num_pages}}
<hr> <br/><br/>
{% if venues.has_previous %}
First Page
Previous
{% endif %}
{% if venues.has_next %}
Next
Last
{% endif %}
</body>
</html>
How do I solve this problem where my hostname value does not get reset and while going back and forth through pages I get consistent values of the hostname I have searched for?

AJAX unable to define the key's method in Django

First off, sorry for the odd phrasing of the title.
I currently have a webapp that allows users to order food from a resturant. In the menu html I currently have the following snippet.
{% if latest_order %}
<table class="table" id="checkout-table">
<thead class="thead-dark">
<tr>
<th scope="col"></th>
<th scope="col">YOUR</th>
<th scope="col">CART</th>
<th scope="col"></th>
</tr>
</thead>
{% for order in latest_order %}
<tr>
<td>{{ order.order_name }}</td>
<td class="change-quantity">
<form method="post">
{% csrf_token %}
<div class="row">
<div class="col-sm">
<button type="submit" name="remove_quantity" value="{{ order.id }}"
class="mr-3 btn btn-outline-info">-</button>
</div>
<div class="col-sm">
{{ order.order_quantity }}
</div>
<div class="col-sm">
<button type="submit" name="add_quantity" value="{{ order.id }}" class="ml-3 btn
btn-outline-info">+</button>
</div>
</div>
</form>
</td>
<td>${{ order.order_individual_price }}</td>
in my JS I have the following AJAX code running
$(document).ready(function(){
$(".ramen").click(function(event){
event.preventDefault()
var serializedData = $("#ramen-form").serialize()
$.ajax({
url: $("ramen-form").data("url"),
data: serializedData,
type: 'post',
success: function(response) {
$("#checkout-table").append('<tr><td>' + response.new_order.order_name + '</td><td class="change-quantity">' +
'<form method="post">{% csrf_token %}<div class="row"><div class="col-sm">' +
'<button type="submit" name="remove_quantity" value="{{ order.id }}"class="mr-3 btn btn-outline-info">-</button>' +
'</div><div class="col-sm">'+ response.new_order.order_quantity +'</div><div class="col-sm">' +
'<button type="submit" name="add_quantity" value="{{ order.id }}" class="ml-3 btn btn-outline-info">+</button>' +
'</div></div></form></td><td>$'+ response.new_order.order_individual_price +'</td><form method="post">{% csrf_token %}<th>' +
'<button type="submit" name="delete" value="{{ order.id }}" class="btn btn-danger">Delete Item</button></th></form></tr>')
}
})
});
})
In my views.py I have the following to return a JsonResponse
get_price = menu_name.Menu_price
get_desc = menu_name.Menu_Desc
new_order = Order.objects.create(
customer=request.user,
order_name=menu_name,
order_individual_price=get_price,
order_default_price=get_price,
order_desc = get_desc,
)
return JsonResponse({'new_order':model_to_dict(new_order)}, status=200)
AJAX returns the following error after I try to add an item to cart
I think the problem is you don't parse the response. So, JQuery doesn't read it becase it is a string, not JSON. You might add the following to your AJAX call to parse it automatically:
$.ajax({
...
dataType: 'json',
success: function(response) {
...
}
}
Since you're using JQuery, you might also use $.parseJSON() to parse response.

How to update template variable in Django

I want to update value of 'log_data_full' from django template, i have extracted updated value in json from AJAX, i dont' want to refresh the page . i just want to update table view with updated value. Is that possible?
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>=Id</th>
<th>Category</th>
<th>Fee</th>
<th>Search</th>
</tr>
</thead>
<tbody>
{% for log in log_data_full %}
<tr>
<td>{{ log.Id }}</td>
<td>13</td>
<td>100</td>
<td>{{ log.search }}</td>
</tr>
{% endfor %}
</tbody>
</table>
AJAX query
$.ajax({
url: "/filter",
type: "POST",
data: {
from_date:from_date,
to_date:to_date,
csrfmiddlewaretoken: '{{ csrf_token }}',
},
success : function(json) {
debugger
if(json != 'error'){
var res = JSON.parse(json);
}
else{
alert('Server Error! Could not get data');
}
},
error : function(xhr,errmsg,err) {
alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
}
});
How to update value by of template variable 'log_data_full'?
Assuming you want to show the updated data in the table received from the server.
in your success function
success : function(json) {
if(json != 'error'){
$("#dataTable").empty(); //remove existing data
var res = JSON.parse(json);
rowHtml = '';
$.each(res, function (i, item) {
rowHtml = '<tr><td>' + res.id + '</td><td>' + res.category + '</td><td>' + res.fee + '</td><td>'+ res.search +'</td></tr>';
});
$('#dataTable').append(rowHtml);
}

table row order are not updatin in the database after ajax call in django

I am using jquery UI .sortable to sort my table rows by drag and drop. I have declare a field map_order in the model as an order update. so the thing is when I am making ajax call to update the model order field. it didn't update it. but when I console log the sort variable it will show the assigning of index to the pk of model.
I have tried to update the filed but it did,nt work
HTML
<tbody id="#layerTable">
{% for layer in layers %} ​
<tr data-pk="{{ layer.id }}" class="ui-state-default"> <td><input type="checkbox" name="ids" value="{{ layer.id }}" /></td>
<td> {{ layer.name }} </td>
<td>{{ layer.heading }}</td>
<td>{{ layer.class_group }}</td>
<td> <span class="glyphicon glyphicon-resize-vertical"></span> {{ layer.map_order }}</td>
<td>{{ layer.map_server }} </td>
<td> {% if layer.sql_schema %}{{ layer.sql_schema }}.{{ layer.sql_table }}{% endif %} </td>
</tr>
​
JS
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("tbody").sortable({
update: function(event, ui) {
​
sort = {};
window.CSRF_TOKEN = "{{ csrf_token }}";
$("tbody").children().each(function(){
sort[$(this).data('pk')] = $(this).index();
});
​
{#var csrftoken = $('input[name="csrfmiddlewaretoken"]').val();#}
$.ajax({
url: "{% url "mapport.maps.layers.all" map.id %}sort/",
type: "post",
data:{sort,
csrfmiddlewaretoken: window.CSRF_TOKEN,
},
​
});
console.log(sort)
},
}).disableSelection();
});
​
</script>
views
#csrf_exempt
def sort(self):
for index, pk in enumerate(self.request.POST.getlist('layer[]')):
layer = get_object_or_404(Layer, pk=pk)
layer.map_order = index
layer.save()
​
return HttpResponse('')
I I have expected to update the field map_order.. but it didn't update. the index is assigning in browser to the id when I drag and drop rows

Django Ajax and Looping over Response

I currently have the following template,
{% extends "123/123-base.html" %}
{% block main %}
<script type="text/javascript">
$(document).ready(function() {
$("#button").click(function() {
var host = $("#hostinput").val();
var record = $("#recordinput").val();
$.ajax({
url : "/lookup_ajax",
type : "POST",
dataType: "json",
data : {
hostinput : host,
recordinput : record,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
$('#mainsection').append( "response" + json.response );
},
error : function(xhr,errmsg,err) {
alert(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
});
</script>
<div id="mainsection">
<div id="maininput" class="input-append">
<form method="post" name="inputlookup" action="/lookup_ajax">
{% csrf_token %}
<input class="span2" id="hostinput" name="hostinput" type="text">
<select title="Record" id="recordinput" name="recordinput" >
<option value="A">A</option>
<option value="MX">MX</option>
<option value="Cname">Cname</option>
</select>
<button id="button" class="btn" type="submit">Lookup</button>
</form>
</div>
<div id="mainouput">
</div>
</div>
{% endblock %}
However the response I receieve back from the server I want to loop over using the Django template tags, like this,
{% extends "123/123-base.html" %}
{% block main %}
{% if error %}
{{ error }}
{% else %}
<ul>
<table class="table table-style table-striped">
<thead>
<tr>
<th>HOSTNAME</th>
<th>TTL</th>
<th>CLASS</th>
<th>TYPE</th>
<th>DETAILS</th>
</tr>
</thead>
{% for answer in response %}
<tr>
{% for field in answer %}
<td>{{ field }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
</ul>
{% endif %}
{% endblock %}
Any ideas on how this should be done ?
Thanks,
It looks to me like you're returning a JSON object for your AJAX call. If that's correct then django doesn't come into it for displaying the result. You'd need to change your success function to something like the following:
success: function(json){
// Table header
var table = $('<table>').addClass('table table-style table-striped');
var thead = $('<thead>');
var headrow = $('<tr>');
var head1 = $('<th>').text('HOSTNAME');
var head2 = $('<th>').text('TTL');
var head3 = $('<th>').text('CLASS');
var head4 = $('<th>').text('TYPE');
var head5 = $('<th>').text('DETAILS');
$(headrow).append(head1, head2, head3, head4, head5);
$(thead).append(headrow);
$(table).append(thead);
// table body
var tbody = $('<tbody>');
num_answers = json.length
for (i = 0; i < num_answers; i++) {
var row = $('<tr>');
var cell1 = $('<td>').text(json[i][0]);
var cell2 = $('<td>').text(json[i][1]);
var cell3 = $('<td>').text(json[i][2]);
var cell4 = $('<td>').text(json[i][3]);
var cell5 = $('<td>').text(json[i][4]);
$(row).append(cell1, cell2, cell3, cell4, cell5);
$(tbody).append(row);
}
$(table).append(row);
$('#mainsection').append(table);
}

Categories