Django, I can't return httpresponse data with ajax on admin change_list view - ajax

Now I added a button to admin panel like in this which open a modal like this with form that takes a pin and I want to return with a balance value in an alert or a modal, but I can't as change_list view in admin django return TemplateResponse not an HttpResponse, when I searched I found that all examples use httpresponse to dump json data, btw Templateresponse inherits from Httpresponse, but what can I do to return balance value here is my code
Note :I'm not good at ajax
This is my template in admin
change_list.html
{% block object-tools-items %}
<li>Balance</li>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Insert your pin</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-lg-12">
<div >
<form class="input-group" style="margin-bottom: 15px;" method="post" action="." id="pinform">
{% csrf_token %}
{{pinform.as_p}}
<span class="input-group-btn">
<button class="btn btn-default" id="PinInput" type="submit" role="button" data-toggle="modal" data-balance="{{balance}}">Go!</button>
</span>
</form>
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
</div><!-- /.row -->
</div>
</div>
</div>
</div>
<div id="balanceModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" >×</button>
<h4 class="modal-title">Balance</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-lg-12">
<div class="input-group" style="margin-bottom: 15px">
<p id="balance">{{balance}} EGP</p>
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
</div><!-- /.row -->
</div>
</div>
</div>
</div>
{{block.super}}
{% endblock %}
my admin change_list view is
admin.py
def changelist_view(self, request, extra_context=None):
extra_context = extra_context or {}
if request.method == 'POST' and request.is_ajax():
form = PinForm(request.POST)
if form.is_valid():
extra_context['pinform'] = form
extra_context['balance'] = form.clean_pin()
response = super(TRANSACTION_DISPLAY, self).changelist_view(request, extra_context=extra_context)
response['balance'] = form.clean_pin()
return response
else:
extra_context['pinform'] = PinForm
return super(TRANSACTION_DISPLAY, self).changelist_view(request, extra_context=extra_context)
else:
extra_context['pinform'] = PinForm()
return super(TRANSACTION_DISPLAY, self).changelist_view(request, extra_context=extra_context)
Change_list.js
$(document).ready(function() {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
$('#pinform').on('submit', function(event){
event.preventDefault();
console.log("form submitted!"); // sanity check
var csrftoken = getCookie('csrftoken');
var pin = $('#inputPin').val();
$.ajax({
url : window.location.href, // the endpoint,commonly same url
type : "POST", // http method
crossDomain: false,
data : { csrfmiddlewaretoken : csrftoken,
pin : pin
}, // data sent with the post request
// handle a successful response
success : function(data) {
// $('#mymodal').modal('hide');
// $('#balanceModal').modal('show');
// console.log(data);
// $('#balance').text(data($('#PinInput').data('balance')));
return data;
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
});});
forms.py
class PinForm(forms.Form):
pin = forms.CharField(max_length=32, widget = forms.PasswordInput(attrs={'class': 'form-control',
'id': 'inputPin'}), label='')
def clean_pin(self):
balance = '200.0' # for simplicity
return balance
Now the form submitted and appear form submitted in console log but I can't grap the data returned from the view

admin.py
if request.method == 'POST' and request.is_ajax():
form = PinForm(request.POST)
if form.is_valid():
extra_context['pinform'] = form
return HttpResponse(json.dumps({'balance': form.cleaned_data['pin']}), content_type='application/json')
else:
extra_context['pinform'] = PinForm()
return super(TRANSACTION_DISPLAY, self).changelist_view(request, extra_context=extra_context)
Change_list.js
$.ajax({
url : window.location.href, // the endpoint,commonly same url
type : "POST", // http method
crossDomain: false,
data : { csrfmiddlewaretoken : csrftoken,
pin : pin
}, // data sent with the post request
// handle a successful response
success : function(data) {
$('#myModal .close').click();
$('#balanceModal').modal('show');
$('#balance').addClass('lead').text(data['balance']);
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
});

Related

Django Python can not upload directory with large quantity of files

I am trying to upload a directory with large number of dicom files using Django and JQuery ajax. Each file size is not more than 600kb. I can upload 200 files at a time. If I increase the number of files (tried to upload 14000 files), it doesn’t work. The site gets stuck and it’s not showing any error. Can anyone please help me with this problem? I have attached my code below. Thanks in advance.
View.py:
def handle_uploaded_file(f,filePath):
with open(filePath+'/'+f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
def UploadScanView(request):
if request.method == 'POST':
form = create_scan_form(request.POST)
if form.is_valid():
scan = form.save(commit=False)
scan.project_id = form.cleaned_data.get('project_id')
directory_name = request.POST.get('directories')
json_to_dictionary = json.loads(directory_name)
print(json_to_dictionary)
for upload_file in request.FILES.getlist('file'):
file_path = settings.MEDIA_ROOT+'/'+os.path.dirname(json_to_dictionary[upload_file.name])
print(file_path)
if os.path.exists(file_path):
handle_uploaded_file(upload_file, file_path)
else:
os.makedirs(file_path)
handle_uploaded_file(upload_file,file_path)
return render(request, 'fileupload/basic_upload/scan_upload.html', {'form': form})
else:
form = create_scan_form()
return render(request, 'fileupload/basic_upload/scan_upload.html', {'form': form})
HTML and JQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script>
/*fileupload div*/
$(document).ready(function(){
$("#my-file").on('change',function(e){ //submit(function(e){
$("#file-wrap p").text('Now click on Upload button');
});
$("#my-form").on('submit',function(e){ //submit(function(e){
files = document.querySelector("#my-file").files;
var directories = {}
for (var file of files) {
file.webkitRelativePath
directories[file.name] = file.webkitRelativePath
}
directories = JSON.stringify(directories);
document.querySelector("#directories").value = directories
var eventType = $(this).attr("method"); // get method type for #my-form
var eventLink = $(this).attr("action"); // get action link for #my-form
//alert(directories);
//////
var formData = new FormData(this);
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
$.ajax({
headers: { "X-CSRFToken": '{{ csrf_token }}' },
type: eventType,
url: eventLink,
//data: new FormData(this), // IMPORTANt
data: formData,
cache: false,
contentType: false,
processData: false,
// this part is progress bar
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (e) {
if (e.lengthComputable) {
var percentComplete = e.loaded / e.total;
percentComplete = parseInt(percentComplete * 100);
$('.myprogress').text(percentComplete + '%');
$('.myprogress').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
success: function(getResult) {
$('#my-form')[0].reset(); // reset form
$("#file-wrap p").html('Drag and drop file here'); // change wrap message
}
});
e.preventDefault();
});
});
/*fileupload div*/
</script>
<form id="my-form" method="POST" action="{% url 'fileupload:upload_scan' %}" enctype="multipart/form-data"> <!--independentSub-->
{% csrf_token %}
<div id="user_form" class="container">
<div class="form-group col-sm-4" id="project_id">
{{ form.project_id|as_crispy_field }}
</div>
<!--fileupload div-->
<div id="independentSubDiv" class="row">
<div id="file-wrap" class="form-group col-sm-6" >
<p>Drag and drop file here</p>
<input id="my-file" type="file" name="file" multiple webkitdirectory directory draggable="true">
<input type="text" id="directories" name="directories" hidden />
</div>
</div>
<div style="padding-left: initial" id="independentSubDiv" class="form-group col-sm-7" >
<button type="submit" class="btn btn-primary btn-lg btn-block" name="submit_btn" id="submit_btn">Submit</button>
</div>
<div class="progress form-group col-sm-7" style="padding-left: initial" id="progressDiv" >
<div class="progress-bar progress-bar-success myprogress " role="progressbar">0%</div>
</div>
</div>
</form>

Symfony redirect by ajax

The page login use ajax, in controller response in view web browser {"response":true,"data":{"from":"apachecms_api_login_submit","to":"/dashboard"}} and not redirect.
function to ajax when success
function beforeSuccess(data){
if(data.data.from=='apachecms_api_login_recovery_submit'){
loading.hide();
$.toast({
heading: "{{ 'success' | trans }}",
text: "{{ 'forgot.password.sending' | trans }}",
position: 'top-right',
icon: 'success',
hideAfter: 5000,
stack: 10
});
changeForm('login')
}else if(data.data.from=='apachecms_api_login_submit'){
location.href=data.data.to;
}else if(data.data.from=='apachecms_api_login_create_submit'){
location.href=data.data.to;
}
}
Whats happend?
LoginController.php extends BaseController
public function loginAction(Request $request){
$form=$this->createForm(LoginType::class, null,array('action'=>$this->generateUrl('apachecms_api_login_submit'),'method' => 'POST'));
$form->handleRequest($request);
if($errors=$this->ifErrors($form)) return $errors;
try {
$entity = $this->getDoctrine()->getRepository('ApachecmsBackendBundle:Customer')->findOneBy(array('email'=>$form->get('_username')->getData(),'isDelete'=>false));
if(!$entity)
throw new Exception(null,200);
$encoder_service = $this->get('security.encoder_factory');
$encoder = $encoder_service->getEncoder($entity);
if(!$encoder->isPasswordValid($entity->getPassword(), $form->get('_password')->getData(), $entity->getSalt()))
throw new Exception(null,200);
$token = new UsernamePasswordToken($entity, $form->get('_password')->getData(), "main", $entity->getRoles());
$this->get("security.token_storage")->setToken($token);
$event = new InteractiveLoginEvent($request, $token);
$this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
return $this->responseOk(array('from'=>'apachecms_api_login_submit','to'=>$this->generateUrl('apachecms_frontend_dashboard'))); // HERE RETURN RESPONSE
}catch (Exception $excepcion) {
return $this->responseFail(array(array('property'=>'_username','code'=>'invalid_credentials','message'=>$this->get('translator')->trans('invalid.credentials'),'data'=>null)),200);
}
}
BaseController.php
public function responseOk($data=array(),$code=200){
try{
// if(!$data)
// throw new Exception('No se encontró el registro',200);
return new Response($this->get('jms_serializer')->serialize(
array('response'=>true,'data'=>$data),
'json',$this->context),$code);
}catch (Exception $excepcion) {
return $this->responseFail(array(array(
'property'=>null,
'message'=>$excepcion->getMessage(),
'code'=>'not_found',
'data'=>null
)),$excepcion->getCode());
}
}
index.html.twig <= Login Page
{{ form_start(formLogin, {'attr': {'id':'loginform','novalidate':'novalidate','class':'form-horizontal form-material sendToApi login'} }) }}
<div class="form-group">
<div class="col-xs-12">
{{form_widget(formLogin._username)}}
<small class="text-danger error">{{ form_errors(formLogin._username) }}</small>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
{{form_widget(formLogin._password)}}
<small class="text-danger error">{{ form_errors(formLogin._password) }}</small>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<div class="checkbox checkbox-info pull-left p-t-0"></div>
<a href="javascript:changeForm('recovery')" id="to-recover" class="text-dark pull-right">
<i class="fa fa-lock m-r-5"></i> {{ 'forgot.password' | trans }}</a>
</div>
</div>
<div class="form-group text-center">
<div class="col-xs-12 p-b-20">
{{form_widget(formLogin.submit,{ 'attr':{ 'class':'btn btn-block btn-lg btn-info btn-rounded','secondary-label':'loading' | trans}})}}
</div>
</div>
{{ include('ApachecmsFrontendBundle::Login/social.html.twig') }}
<div class="form-group m-b-0">
<div class="col-sm-12 text-center">
{{ 'not.account' | trans }}
<a href="javascript:changeForm('register')" class="text-info m-l-5">
<b>{{ 'register' | trans }}</b>
</a>
</div>
</div>
{{ form_end(formLogin) }}
Ajax
// pre-submit callback
function showRequest(formData, form, options) {
loading.show('{{ 'loading' | trans }}');
var url = form.attr("action");
var method = form.attr("method").toUpperCase();
var dataForm = form.serialize();
var submitBtn = form.closest('form').find(':submit');
var inputs=form.closest('form').find(':input:not(.dropify)');
inputs.removeClass('error');
inputs.next('small').html('');
BtnSecondaryLabel=submitBtn.attr('secondary-label');
BtnHtml=submitBtn.html();
submitBtn.html('<i class="fa fa-gear fa-spin"></i> '+BtnSecondaryLabel);
submitBtn.attr('disabled',true);
return true;
}
// post-submit callback
function showResponse(data, statusText, xhr, form) {
var submitBtn = form.closest('form').find(':submit');
submitBtn.attr('disabled',false);
submitBtn.html(BtnHtml);
if(data.response==true){
beforeSuccess(data);
}
}
$(function (){
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
$( "form.sendToApi" ).ajaxForm(options); <= capture class to form sendToApi
})
function beforeSuccess(data){
if(data.data.from=='apachecms_api_login_recovery_submit'){
loading.hide();
$.toast({
heading: "{{ 'success' | trans }}",
text: "{{ 'forgot.password.sending' | trans }}",
position: 'top-right',
icon: 'success',
hideAfter: 5000,
stack: 10
});
changeForm('login')
}else if(data.data.from=='apachecms_api_login_submit'){
location.href=data.data.to;
}
}

I have a probllem when the button delete has clicked but the data cannot delete and the url not show the id

I have tried to solve this problem several hours but I never solve this problem
I have a problem with my code, when I click the delete button from json, I can't get the ID just link from the console like this:
example :
That happened : request
I want Like this : request/?id=1
I paste some code to check :
Controller request.php:
public function delete()
{
// $this->m_request->delete($this->input->post('id_form'));
$id = $this->input->post('id_form');
$data = $this->m_request->DeleteRequest($id);
echo json_encode($data);
}
Model m_request.php:
public function DeleteRequest($id)
{
$hasil = $this->db->query("DELETE FROM request WHERE id_form='$id'");
return $hasil;
}
And Then View (I just put the modal script and ajax json script) :
Modal View :
<div class="modal fade" id="ModalHapus" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Hapus Request</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">X</span></button>
</div>
<form class="form-horizontal">
<div class="modal-body">
<input type="hidden" name="kode" id="textkode" value="">
<div class="alert alert-warning">
<p>Apakah Anda yakin mau menghapus request ini?</p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button>
<button class="btn_hapus btn btn-danger" id="btn_hapus">Hapus</button>
</div>
</form>
</div>
</div>
Ajax/JSON Script :
//GET HAPUS
$(document).on('click', '.hapus', function() {
var id = $(this).attr('data');
$('#ModalHapus').modal('show');
$('[name="kode"]').val(id);
})
// Hapus Request
$('#btn_hapus').on('click',function(e){
e.preventDefault();
var id = $('textkode').val();
$.ajax({
type: "POST",
url: "<?= site_url('request/delete')?>",
dataType: "JSON",
data: {id:id},
success: function(data){
// $('#ModalHapus').modal('hide');
console.log(data)
load_data();
}
});
return false;
})
There are a lot of reasons why the ajax request is possibly not working. The first thing which came in my mind is, that you have not specified an ID and method of the input form. Make sure you have both in your HTML form tag. For example:
<form id=“id_form” method=“post” class=“...”>
...
<input type="text" name="kode" id="textkode">
</form>
In you JS Code do the following
$.ajax({
type: "POST",
url: "<?= site_url('request/delete')?>",
dataType: "JSON",
data: $(“#id_form”).serialize(),
success: function(data){
console.log(data)
load_data();
}
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nERROR: "+ err);
}
});
Also change the your delete function to this:
public function deleteTableRow()
{
$id = $_POST['textkode']; // Because I'm not sure what this->input->post() makes
$result = $this->m_request->DeleteRequest($id);
echo json_encode(array('id' => $id, 'result' => $result)); // The contents of array should then be displayed in the console of your webbrowser
}
Note that I changed the function name. It could be very misleading for other programmers, because delete is used in many programming languages as destructor for dynamic objects!
Additionally I would recommend to create an ajax.php file to parse different kind of ajax request. This file would also work as a controller, but just for ajax calls. In case you have several forms, the code is more readable.

Using Ajax and Django conditions to display an html variable

I'm new to using Ajax calls with Django. Im trying to implement a simple Display or not display depending on the type of get called by Ajax:
Views:
def dynamic(request):
context = {}
if request.method == 'GET':
if 'backtest_type' in request.GET:
context['display_details'] = False
print ('Im not displaying')
elif 'change_val' in request.GET:
context['display_details'] = True
print ('Im displaying')
else:
context['display_details'] = False
return render(request, "demo/dynamic.html", context)
In my template:
{% extends 'demo/base.html' %}
{% block body %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="{% static 'css/dynamic.css' %}">
<script>
$(document).on('click','#id_backtest_type', function () {
console.log( $(this).val() );
$.ajax({
type: 'get',
data: {'backtest_type': 1},
success: function (data) {
console.log('data sent ' + data);
},
failure: function(data) {
alert('Got an error dude');
}
});
});
$(document).on('click','#btnClick', function () {
// console.log( $(this).val() );
$.ajax({
type: 'get',
data: {'change_val': 1},
success: function (data) {
console.log('data sent ' + data);
failure: function(data) {
alert('Got an error dude');
}
});
});
</script>
<div>
{% if display_details %}
<h1>I'm diplaying</h1>
{% endif %}
</div>
<div id="btnClick" class="col-sm-4">
<div class="btn-group btn-group-justified" role="group">
<div class="btn-group" role="group">
<button class="btn btn-secondary" type="button">Don't Display</button>
</div>
</div>
</div>
<div id="id_backtest_type" class="col-sm-4">
<div class="btn-group btn-group-justified" role="group">
<div class="btn-group" role="group">
<button class="btn btn-secondary" type="button">Display!</button>
</div>
</div>
</div>
{% endblock %}
From the console I'm sure that the get requests are being correctly sent using ajax (the get requests are being sent and the console prints the statements:
[09/Feb/2019 20:00:56] "GET /dynamic/?backtest_type=1 HTTP/1.1" 200
6530
Im displaying
However, even if the ajax call works correctly, the template doesn't end up rendering <h1>I'm diplaying</h1>. Am I misunderstanding anything about Ajax?
Thanks in advance!

Adding records to a drop down menu without form refresh

I want to add records to a drop down menu without form refresh. I'm using codeigniter and bootstrap
Here is the Bootstrap Modal :
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
<h4 id="myLargeModalLabel" class="modal-title">Add Record</h4>
</div>
<div class="modal-body">
<form class="sky-form" id="sky-inchidere" method="post" accept-charset="utf-8" action="">
<dl class="dl-horizontal">
<dt>Name<span class="color-red">*</span></dt>
<dd>
<section>
<label class="input">
<i class="icon-append fa fa-inbox"></i>
<input type="text" value="" name="name" required>
<b class="tooltip tooltip-bottom-right">Add New Record</b>
</label>
</section>
</dd>
</dl>
<hr>
<button type="submit" class="btn-u" style="float:right; margin-top:-5px;">Submit</button>
</form>
</div>
</div>
</div>
Ajax script :
$(document).ready(function(){
$("#sky-inchidere").submit(function(e){
e.preventDefault();
var tdata= $("#sky-inchidere").serializeArray();
$.ajax({
type: "POST",
url: 'http://localhost/new/oportunitati/add',
data: tdata,
success:function(tdata)
{
alert('SUCCESS!!');
},
error: function (XHR, status, response) {
alert('fail');
}
});
});
});
CI Controller ( i have added the modal code here for test )
public function add() {
$tdata = array( name=> $this->input->post(name),
);
$this->db->insert('table',$tdata);
}
When i use this code i get "fail" error message.
Thanks for your time.
how yo debug:
1. Print your 'tdata' and see what happen;
2. Something wrong here: $this->input->post('name');
Try to use:
$tdata = array(
'name' => $this->input->post('name')
);
I manage to find the problem and correct it. (typo on the table name)
Now I have come across a different problem. In the ajax success I cant refresh the chosen dropdown records i have tried :
success:function(tdata)
{
// close the modal
$('#myModal').modal('hide');
// update dropdown ??
$('.chosen-select').trigger('liszt:updated');
$('#field-beneficiar_p').trigger('chosen:updated');
$('#field-beneficiar_p').trigger('liszt:updated');
},
Any help in how i can refresh the records to see the last added item will be appreciated. I'm using chosen plugin.
from controller send data in json_encode
then in js function
$.ajax({
type: "POST",
url: "<?php echo base_url('login/get_time'); ?>",
data: {"consltant_name": consltant_name, "time": time},
success: function(data) {
var data = JSON.parse(data);
var options = '';
options = options + '<option value="">Please Select One</option>'
$.each(data, function(i, item) {
options = options + '<option value="' + item + '">' + item + '</option>'
});
selectbox.html(options);
}});

Resources