I’m working with Django
in a project and I need to execute some functions depending on what user’s want to do. If this action has to return and show new values I know how to do it, but when I just want to execute a function in my views.py
that I don’t need any response and don’t know how to do it.
Now what I’m doing is return something and don’t use it, but I’m sure it is possible do it without returning anything.
My code that returns a response is:
$('#import_btn').click(function(){
updateData()
});
function updateData(filt){
console.log('Hello');
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
$.ajax({
url: '/../../updateBBDD/',
type: 'POST',
headers:{"X-CSRFToken": csrftoken},
data: {
'Filt': filt,
},
dataType: "json",
cache: true,
success: function(response) {
var cols = response.Cols;
}
});
}
How I have to do it in my js
to execute a python function with no response??
Thank you very much.
2
Answers
I think you overcomplicate things. The HTTP protocol [wiki] is a request-response protocol. So normally, each request is followed by a response. That response can be empty, denote a problem, etc.
You thus can define a view function that does something, and returns an empty
HttpResponse
object [Django-doc]:Your front-end code (js) doesn’t know anything about Python – all it’s doing is sending an HTTP request to a given url (and it of course expects a response – that’s the very basis of HTTP). The fact that this request actually triggers the execution of some Python code is totally orthogonal – as far as your js code is concerned, the response could also just be Apache or nginx etc returning a file’s content, or some proxy server returning a response from a cache, etc.
So on the front side, your js code sends a request and it expects a response (whatever the response content is). This tells the j code that the request has been received and processed one way or another.
On the Python/Django side, a Django "view" is a "request handler" – a callable (function, method or else) that takes an incoming request and returns a response. Note that this last part is mandatory – if your view doesn’t return a response, you’ll get an exception. What this response contains is up to you (the content can be totally empty), but you must return it.
Note that even if the response content is actually empty, the response will always hae a status code (200 being the default) telling the client (your js code or whatever) whether the request was "correctly" handled or if anything went wrong. So you probably don’t want to ignore the response’s status_code (at least) in your client code, nor blindly return a 200 whatever happened in the backend – if something didn’t worked as expected, you certainly want to notify the user…
Given your question, I strongly suggest you read the HTTP specs. Trying to do web programming without a decent understanding of the protocol isn’t going to yield great results…