In my Django project, I have an Ajax request that returns a JSON response. When there is an error, I would like to present the error text, as well as a link. Something like "There was a problem, please click here". I don't know how to get the link in the JSON, however. Maybe I am thinking about this wrong - any help is appreciated!
Ajax call:
$.ajax({method: 'POST', url:'/update_count/' + meals, data:{csrfmiddlewaretoken: "{{ csrf_token }}", 'auto-update': auto_update}}).done(function(data) {
if(data['type'] === 'error'){
$('#error-message').html(data['message'])
}
View
return JsonResponse({'type': 'error', 'message': 'Only registered users can use this feature. Please click ???????? for more information.'})
I think that what you're trying to do is best done in the client, and not constructed in the srever.
You should return the url in the json response, and then parse that response in your HTML code.
response = {
'type': 'error',
'url': <url>
}
That way you can wrap the url in an <a></a> tag for example in your HTML, or do a million other things to show the user that he has to register.
If you still want to have the html tags in your response, you could use Django filters, which allow you to add HTML to your responses
Related
I have seen many answers to questions like this, but none has solved my problem...
I want to produce a pdf in the backend and then download it to the user.
So I have a basic blank page with a button. For that button there is a jQuery function:
$.post("{% url 'printReport' %}",
{
'params' : JSON.stringify({
'reportcode' : 'HelloWorld',
})
}, function(data, status) {
$("#testZone").text(data)
});
On the server side, I produce the pdf and save it locally in the server folder. This goes perfect.
Then, in the views file I have this:
def printRreport(request):
if request.method=="POST":
res = producePdf(request) #works fine! the PDF is birght an shiny, saved on the server
response = HttpResponse(res.data,content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="report.pdf"' #setting response headers
return response
where res.data is actually open(pdf_path,'r').read()
this is 70% fine, because the browser actually receives the pdf data inside the request response (I can see it on the dev console). It's 30% wrong because this does not give me a download dialog and does not allow me to save a pdf file on the client side.
What is wrong here? In my case I opted by using a POST method, I know it's debatable, but I don't think that is the problem...
Edit: I found a solution for this, maybe not optimal, but it works.
I marked below the answer I ended up following. I kept the code above, but I decided to generate the pdf file on the first view (which receives the POST request), then redirect the user to another view where it would download it. And it works!
I'll still check this as suggested by Abdul though.
Thanks!
Instead of using HttpResponse try using FileResponse:
from django.http import FileResponse
def printRreport(request):
res = producePdf(request)
file_ptr = # something that would get you something like open(pdf_path,'rb')
return FileResponse(file_ptr)
Now in your javascript the problem is you are making the request as ajax and the content is with javascript, an easier thing would be to let your browser handle the url (It is a file download anyway no need for ajax):
var link = document.createElement("a");
link.download = "Report";
link.href = "{% url 'printReport' %}";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
Note: If you don't need to run this dynamically consider just an anchor with the url. Instead of javascript.
Forgive me for stupid questions, but I do not really understand how such relationships work in the Web-development.
I have views.py:
As you can see there is a connection to the api and the information I need is parsed.
Then in my template I have a listener that shows when the user reached the bottom of the page:
As you can see at the bottom of the template i have ajax block where I again connect to api
But now the most important question is this the right way?
Do I need to connect json and fill my arrays and elements in the ajax block one time more? BUT It's all done in views.py.In general, is it realistic to call def main(request) from ajax all the time and append all my arrays and elements automatically? I need like smth this :
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() == $(document).height()) {
$.ajax({
url: "{% url 'main' %}",//my request which appends all my arrays automatically
type: "GET",
success: function () {
},
error: function () {
});
Sorry for such questions but I do not understand how such bundles work
As for the counter of connected pages, I'll deal with this later, I need information now in which direction to move in general
It's not a good way. Generally, Django view does not have anything to do with it. You should directly call the URL from ajax and parse the answer in your JS, on the page itself. However, if it is necessary to process the response from that URL in some way, then you should create a separated view that will process the response and return the corresponding JSON as a response.
So the first view only needs to have a template response, and your ajax script on the page should call another view and take over from JSON. This second view sends the request to that remote URL and processes it, then returns JSON as a response.
For this other view, I recommend Django Rest Framework, but this is not necessary if it's a simple feature.
I'm using Flask with Flask-Security (specifically Flask-WTF regarding my csrf issue) to "ease" the process of register/loggin users (not easy so far). I'm using BackboneJS on the front-end, therefore I kind of hacked the original way to use Flask-WTF. Indeed, I make an AJAX GET request on /register to get the register page (generated by Flask-Security) and I put the resulting HTML in a modal.
render: function () {
var self = this;
$.ajax({
type: 'GET',
url: Config.constants.serverGateway + "/register"
}).done(function(result){
console.log("get register done", result);
var html = self.template({ config: Config, form: result });
self.$el.html(html);
}).fail(function(error){
console.log("Could not get register token", error);
var html = this.errorTemplate({ config: Config });
self.$el.html(html);
});
return this;
}
This way I have the generated csrf, and when I POST the registration data, I send the right csrf along the user data (email and password).
submit: function () {
console.log("submit");
var self = this;
var formData = this.$el.find('form').serialize();
$.ajax({
type: 'POST',
url: Config.constants.serverGateway + "/register",
data: formData,
dataType: 'json'
}).done(function(result){
self.trigger('close');
}).fail(function(error){
console.log("Could not submit register data", error);
});
}
On the server-side, I can debug my python code to see that the csrf_token which has been generated when I requested the register page has disappeared from the session object, therefore leading to the generation of a new one, which of course didn't match the one I send with my form. The session is still the same though, as the _id is the same during the GET and the POST.
You can see the code in flask_wtf/csrf.py::generate_csrf(), which is called when creating the form object in the ::register function from flask_security/views.py
if 'csrf_token' not in session:
session['csrf_token'] = hashlib.sha1(os.urandom(64)).hexdigest()
It results in a CSRF TOKEN MISSING error.
An additionnal information, is that my front-end and back-end are delivered by the same server, as they have a different port number.
Last, when I use an href on front-end and display the page returned by the server on the 'GET' request, submitting the form works well. I just liked to display this registration form in a modal.
Thanks for your help
Okay, I finally figured out the solution to my problem. I feel like a noob (which I am).
The problem lied in the session credentials which were not sent to the server with the requests, so that the server coudldn't access the session cookie.
I found the solution in the following tutorial: http://backbonetutorials.com/cross-domain-sessions/
To send it, i added the following lines in my Backbone router initialize function:
// Use withCredentials to send the server cookies
// The server must allow this through response headers
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
options.xhrFields = {
withCredentials: true
};
});
This makes all AJAX requests include the withCredentials = true. On the server-side, I had to set Access-Control-Allow-Credentials:true. Since I'm using flask-cors, it is done with [supports_credentials=True][2] when creating the CORS object.
(I'm answering here since I can't comment)
#junnytony Yes I have the token in my modal and I send it in my POSt request. When I debug the Flask application, I can see the toekn I sent with my POST request, the problem is that it should be compared to the one in the session to be validated, but the one in the session has disappearred, so the flask-wtf lib generates a new one, which results in a failure when comparing with the one I sent.
Alright, I'm working with a RESTful backend on my project, and submitting data via jquery.
I must say the werkzeug debugger is excellent for debugging specially when you're a terrible python programmer as me. You throw an exception on purpose where you want to investigate, and inspect the code and variables using the html the debugger rendered.
However when you send a post request instead of a get, if you throw an exception on the backend code, of course, the browser won't render the response text.
Is there any technique I can use to render the response text, considering it has javascript and everything?
I'm trying different things such as trying to inject the response text into a popup window, like:
$.postJSON = function(url, data, callback, error_callback) {
return jQuery.ajax({
'type': 'POST',
'url': url,
'contentType': 'application/json',
'data': JSON.stringify(data),
'dataType': 'json',
'success': callback,
'error': error_callback
});
};
$.postJSON('/the_uri', {'foo': 'bar'},
function(response) {
var a = 0;
},
function(response) {
var html = response.responseText;
var my_window = window.open('', 'mywindow1', 'width=350,height=150');
$(my_window.document).find('html').html(html);
});
});
But this won't take care of the javascript very well.
Does anyone have any suggestion?
Your approach was nearly correct. I am using the following code to open the response text in a new window (not specific to Werkzeug or Flask at all):
var w = window.open('', 'debug_stuff', 'width=540,height=150');
w.document.open();
w.document.write(response.responseText);
w.document.close();
The last line is the most important. Without it, the code would behave as yours -- it would not execute any JavaScript, because the browser doesn't know the DOM has been fully loaded.
Not javascript, but have you tried to use Firebug, you can use the option for viewing the response in a new tab (Open Response in New Tab).
If you're ready to make some changes on both the client and the server code, you can try this. In your error callback you would re-send the JSON data but as a synchonous form submission. You would create the form using jQuery, give it an input tag and put your JSON in that and submit the form. Something like:
$('<form method="post" style="display:none;">')
.attr('action', 'xxx')
.append(
$('<input>').val(JSON.stringify(data))
).appendTo('body')
.submit();
On the server-side, you would have to accept JSON the regular way when the request's content type is application/json and as form data, eg:
json_string = request.form.get('__json')
if json_string:
data = json.loads(json_string)
I have never tried this but I know the problem you're having and it can waste a lot of time. If you try it I'd like to know how it works out.
Markus' answer works perfectly. thanks so much! this saved me so much hassle.
also consider assigning your handlers to a jqxhr object
http://api.jquery.com/jQuery.post/#jqxhr-object
var jqxhr = $.post(...)
then you would write to your new window
w.document.write(jqxhr.responseText);
my ajax code:
$.ajax({
type: 'POST',
url: URL + "xyz/" ,
data: {"email": email},
success: function(data) {
alert('hello')
},
dataType: "json",
});
my handler in python + bottle framework:
def index():
if request.POST == XMLHttpRequest:
email = request.GET.get('email')
response.COOKIES['email'] = email
if check_email(email): //a method written for checking email
return some template
else:
return False //here i want to return some error message to ajax. How to
do it? And How to caught the error in ajax.
throwing error: NameError("global name 'XMLHttpRequest' is not defined",)
is bottle support it?
2 things. First, I don't see why you're trying to check to see if it's an XMLHTTPRequest? I would just check to see if data has been sent via POST. Also it looks like you're sending through POST but trying to retrieve through GET. Try:
def index():
if request.method == "POST":
email = request.POST['email']
response.COOKIES['email'] = email
if check_login(email):
return some template
else:
return False
Just return a regular 404 or 500 response. The web browser is smart enough to know about that, and calls the error callback defined in the javascript code.
For jQuery, I believe the callback is global, but I'm not sure as my jquery-fu is weak.
It doesn't make sense to check "XmlHttpRequest" in Python. That's a Javascript wrapper around a piece of browser functionality, not anything that Python knows or cares about.
If you really need to check that the POST is coming from Ajax, you can check the request headers - jQuery, like other JS frameworks, always sets a HTTP_X_REQUESTED_WITH header. And, in fact, there's an example that uses that exact header on the Bottle documentation for Accessing Request data.