Django Ajax post 500 internal error - ajax

i hope you can help me, im trying to make a django post form without reloading the page using ajax, but im getting error 500 when submit, can you help me to fix this, this is my code:
models.py
class ProductoConcepto(models.Model):
producto = models.ForeignKey(Producto)
orden = models.ForeignKey(Cobro)
cantidad = models.FloatField()
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from cobro import views
urlpatterns = [
url(r'^cobro/agregar_concepto/$', views.addconcept_product, name='add_concepto'),
]
views.py
def addconcept_product(request):
if request.method == 'POST':
if form.is_valid():
producto = request.POST['producto']
orden = request.POST['orden']
cantidad = request.POST['cantidad']
ProductoConcepto.objects.create(producto=producto, orden=orden, cantidad=cantidad)
return HttpResponse('')
template
<div class="modal inmodal fade" id="myModal1" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-m">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Cerrar</span>
</button>
<h3 class="modal-title">Agregar nuevo concepto</h3>
</div>
<div class="modal-body">
<p>Datos de concepto a agregar:</p>
<div class="doctorformstyle">
<form id='formulario-modal' method='post' enctype='multipart/form-data'>
{% csrf_token %}
<ul>{{form2.as_p}}</ul>
<!-- rendered form2 fields: <select id="id_producto" name="producto"><option value="1" selected="selected">object</option></select> -->
<!-- form2 fields: <select id="id_orden" name="orden">
<option value="1" selected="selected">object</option>
</select> -->
<!-- form2 fields: <input id="id_cantidad" name="cantidad" step="any" type="number"> -->
<div class="row align-center">
<input type='submit' name="save1" value='Guardar' class="btn btn-w-m btn-primary"/>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).on('submit', '#formulario-modal', function(e){
e.preventDefault();
$.ajax ({
type: 'POST',
url: '{% url 'add_concepto' %}',
data: {
producto: $('#id_producto').val(),
orden: $('#id_orden').val(),
cantidad: $('#id_cantidad').val(),
csrfmiddlewaretoken: '{{ csrf_token }}',
},
sucess:function(){
alert("OK");
}
})
});
</script>
this is the error: POST http://127.0.0.1:8000/cobro/agregar_concepto/ 500 (Internal Server Error)
I think that maybe something is missing in my view, buy i dont know that, cal you help me?
Edit: Traceback added
Environment:
Request Method: GET Request URL:
http://127.0.0.1:8000/cobro/agregar_concepto/
Django Version: 1.9.7 Python Version: 2.7.11 Installed Applications:
('django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles', 'entrada',
'cobro', 'catalogo', 'selectize', 'smart_selects') Installed
Middleware: ('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in
get_response
158. % (callback.module, view_name))
Exception Type: ValueError at /cobro/agregar_concepto/ Exception
Value: The view cobro.views.addconcept_product didn't return an
HttpResponse object. It returned None instead.

You view is not complete:
As the exception states: The view cobro.views.addconcept_product didn't return an proper HttpResponse object.
return HttpResponseRedirect('/thanks/')

Are you viewing the exception you provided in a new window? Because it is showing
"Request Method: GET" which shouldn't be happening via your ajax function.
Modify your view to this:
def addconcept_product(request):
if request.method == 'POST':
if form.is_valid():
producto = request.POST['producto']
orden = request.POST['orden']
cantidad = request.POST['cantidad']
ProductoConcepto.objects.create(producto=producto, orden=orden, cantidad=cantidad)
return HttpResponse('Product Created')
else:
return HttpResponse('Product Creation failed')
else:
return HttpResponse('Failed: Post requests only.')

Update your return statement with something like.
return HttpResponse('Product Created !')
Also as you are using ajax, you can also return a JsonResponse.
First import it
from django.http import JsonResponse
and then return your response
JsonResponse({'success': 'Product created'})
The exception is getting raised because you are not handling the condition if the method is not POST, and you are submitting a GET request.
Handle the cases for invalid form and if method is not POST.
def addconcept_product(request):
if request.method == 'POST':
if form.is_valid():
....
return JsonResponse({'success': 'Product created'})
else:
return JsonResponse({'error': 'InValid Form.Product Creation Failed'})
else:
return JsonResponse({'error': 'Only POST method allowed'})
Also use ajax method attribute instead of type.
$.ajax ({
method: 'POST',
url: '{% url 'add_concepto' %}',
....
});

Related

how to request django post method values using ajax

I would like to implement simple django login method using ajax. when i want to retreive html input values using ajax in views, the request.post values are returning None. for ex print(request.POST.get('username')), it returns None.
my html form
<form action="" method="POST">{% csrf_token %}
<input type="text" name="username1" class="form-control rounded-1" id="id_username1" value="">
<input type="password" name="password1" class="form-control rounded-1" id="id_password1" value="">
</div>
<input type="button" id="btnlogin" value='Valider'>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.2/jquery.min.js"></script>
<script>
var token = '{{csrf_token}}';
//login
$('#btnlogin').click(function(){
//alert("/login");
$.ajax({
url: "{% url 'login' %}",
headers:{'X-CSRFToken':token},
method:"POST",
data:{},
dataType: 'json',
success: function (data) {
if (data.status){
console.log('Success');
}
else{
console.log("login failed");
}
}
});
})
</script>
urls.py
path('login/', views.login_page, name='login'),
views.py
def login_page(request):
if request.method == 'POST':
username = request.POST.get('username1')
password = request.POST.get('password1')
print('password :',password)
#result "password : None"
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return JsonResponse({'status':True})
else:
return JsonResponse({'status':False})
context = {}
return render(request, 'core/login.html', context)
I do not know where is the error and how to fix this issue.
Thanx in advance.
i tried request.POST['password1']#result None
i changed to GET method. same issue.
I would like to collect forms input values in django view method using ajax

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>

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.

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

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
}
});
});

Django - Ajax modal login/registration

I have a project in which I need to pop a modal window for not authenticated users.
This modal will allow to login directly or create an account.
So it will contain two forms:
django.contrib.auth.forms.AuthenticationForm
registration.forms.RegistrationForm
Here is my view to get both forms:
def ajax_registration(request):
obj = {
'login_form': AuthenticationForm(),
'registration_form': RegistrationForm(),
}
return render(request, 'common/ajax_registration.html', obj)
And my template displaying the forms tabbed
<ul class="nav nav-tabs">
<li>{% trans 'Login' %}</li>
<li>{% trans 'Registration' %}</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab1">
{{ login_form|bootstrap }}
</div>
<div class="tab-pane" id="tab2">
{{ registration_form|bootstrap }}
</div>
</div>
Question is: Since I'm using ajax to display this modal, How can I validate the selected form, preferably using the already written django-registrations register & django.contrib.auth login views ?
In addition to Maddog's answer you need some javascript to submit the form back to the URL that rendered the form. Using jquery it could be something like:
$('form').submit(function(e){
e.preventDefault();
var form = $(e.target);
$.ajax({
url: '{% url YOUR_REGISTRATION_URL %}',
type: 'post',
data: account_form.serialize() + '&' + form.serialize(),
error: function(xhr, ajaxOptions, thrownError){ alert(thrownError); },
success: function(){}
})
})
You don't need to do it with a form submit element, you could use any element with $().click(), of course.
Something like this?
def ajax_registration(request):
login_form, registration_form = False, False
if request.method == "POST":
if "email" in request.POST: # some condition to distinguish between login and registration form
login_form = AuthenticationForm(request.POST)
if login_form.is_valid():
# log in
else:
registration_form = RegistrationForm(request.POST)
if registration_form.is_valid():
# register
obj = {
'login_form': login_form if login_form else AuthenticationForm(),
'registration_form': registration_form if registration_form else RegistrationForm(),
}
return render(request, 'common/ajax_registration.html', obj)

Resources