Render template in Django view after AJAX post request - javascript

I have managed to send & receive my JSON object in my views.py with a POST request (AJAX), but am unable to return render(request, "pizza/confirmation.html"). I don't want to stay on the same page but rather have my server, do some backend logic on the database and then render a different template confirming that, but I don't see any other way other than AJAX to send across a (large) JSON object. Here is my view:
#login_required
def basket(request):
if request.method == "POST":
selection = json.dumps(request.POST)
print(f"Selection is", selection) # selection comes out OK
context = {"test": "TO DO"}
return render(request, "pizza/confirmation.html", context) # not working
I have tried checking for request.is_ajax() and also tried render_to_string of my html page, but it all looks like my mistake is elsewhere. Also I see in my terminal, that after my POST request, a GET request to my /basket url is called - don't understand why.
Here is my JavaScript snippet:
var jsonStr = JSON.stringify(obj); //obj contains my data
const r = new XMLHttpRequest();
r.open('POST', '/basket');
const data = new FormData();
data.append('selection', jsonStr);
r.onload = () => {
// don't really want any callback and it seems I can only use GET here anyway
};
r.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
r.send(data);
return false;

In your basket view function, you always render the template as response. You can pass the parameters to your js snippet via HttpResponse. After request completed and you have response in your js function, you can use window.location.href to redirect the page you want. You can also look this answer to get more information.

Related

Refresh a django subtemplate with javascript - reload only part of the page

I'm trying to refresh a subtemplate by calling a view with js. Nothing seems to happen, though the server gets hit and seems to return a response.
The goal is to refresh the included part without refreshing the whole page.
Minimal example:
views.py
def ajax_view(request):
context = {}
context['data'] = 'data'
return render(request, "test.html", context)// <-- reaches here, but no rendering
test.html
{{data}}
main.html
<script type="text/javascript">
function getQuery() {
var request = new XMLHttpRequest(),
method = 'GET',
url = '/ajax/';
request.open(method, url);
request.send();
}
</script>
{% include "test.html" %} // <-- does not update
With the help of a friend, I solved this.
I'm going to answer my question with some detail, because I am 100% sure someone is going to need to figure out how to do this later. Happy to save you the trouble.
I had to change my mental model about how this works.
I still send a request to the server with javascript, and the view returns the templated HTML.
However, and this is the important part, what I do is take the rendered HTML (from the response, what is returned with return render(response, "your_template.html", context)) and replace that part of my page with that HTML.
Here's the Javascript.
function getQuery(item) {
// Sends a request to the API endpoint to fetch data
let request = new XMLHttpRequest();
let method = 'GET';
let query = // omitted
let url = '/ajax/?' + query;
request.open(method, url);
request.onload = function () {
// the response is the rendered HTML
// which django sends as return render(response, "your_template.html", context)
let myHTML = request.response;
// This is the important part
// Set that HTML to the new, templated HTML returned by the server
document.getElementById('flex-container-A').innerHTML = myHTML;
};
request.send();
}
and for completeness, here's the view:
views.py
def ajax_view(request):
"""
Server API endpoint for fetching data
"""
context = {}
queryset = Form.objects
if request.method == 'GET':
query = request.GET.get('q')
# do some stuff and get some data
context['data'] = data
return render(request, "my_template.html", context)
Hope this helps you! This is a common pattern but not often mentioned so explicitly.

Display Progressbar In Django View When downloading video (youtube-dl)

I am calling 'search/' when button is clicked through ajax call. Now my question is i want to show these details {"file_name":d['filename'],"percentage":d['_percent_str'],"speed":d['_eta_str']} in a progress bar while downloading in a web page.
How should i get the json response from video_progress_hook each time it is call by 'progress_hook' parameter in ydl_opts?
I want to get response in javascriprt.
Please help.
def search(request):
file_name=""+str(uuid.uuid1()).split('-')[0]+".mp3"
query=request.GET.get("query")
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192'}],
'outtmpl': 'media/'+file_name,
'progress_hooks':[video_progress_hook],
'quiet': False,
}
ydl = youtube_dl.YoutubeDL(ydl_opts)
ydl.download([query])
args={'url_link':file_name}
return JsonResponse(args)
def video_progress_hook(d):
args={}
if d['status'] == 'downloading':
args={"file_name":d['filename'],"percentage":d['_percent_str'],"speed":d['_eta_str']}
return JsonResponse(args)
In general there is no easy solution.
You need to store you request in db and return that id to the client. After that you need to create special endpoint that returns progress using request id. In your code you should update that request every n seconds.
I think a good solution could be https://github.com/czue/celery-progress

Passing variable between view and JS; Django

I am first passing a JS variable 'confirmed' to my Django view via POST request.
I then run a python script which takes this variable and does some processing.
Finally I want to pass it back to my html/JS so I can display the processed data.
I am currently trying to use Django sessions to achieve my goal but there is a '1 session delay', so the session variable which I update is returning as the value from the previous session.
Is there a better way I can pass the variable from my view to JS/a fix for my current solution?
VIEW:
def crossword(request):
if request.method == 'POST':
Session.objects.all().delete()
str_squares = (request.body).decode('utf-8')
squares = [int(i) for i in str_squares.split(',')]
letters = puzzle_solver.solve_puzzle(3, squares)
# print(letters)
for each_square in letters.keys():
request.session[each_square] = letters[each_square]
request.session.modified = True
return render(request, 'crossword.html')
JS:
// Output a list of active squares
var xhr = new XMLHttpRequest();
var generate = { Generate:function(){
var confirmed = [];
for (i=0; i<active_boxes.length; i++){
confirmed.push(active_boxes[ i ].id_num);
}
console.log(confirmed);
xhr.open("POST", "http://localhost:8000/", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(c=confirmed);
console.log("{{ request.session.keys }}")
console.log("{{ request.session.values }}")
var tester = parse_session_keys("{{ request.session.keys }}");
console.log(tester);
solve_crossword(tester);
}};
Is there a reason why you are not sending the response directly back to JS? In your views.py, you can do
from django.http import JsonResponse
def crossword(request):
if request.method == 'POST':
str_squares = (request.body).decode('utf-8')
squares = [int(i) for i in str_squares.split(',')]
letters = puzzle_solver.solve_puzzle(3, squares)
return JsonResponse(letters)
return render(request, 'crossword.html')
After sending your request, wait and read the response directly as JSON then play with it in your JS code, as described in this post.
If there is any reason preventing you from doing this (for example there might be a form also makes POST requests to the same page thus you need to eventually land on rendering the crossword template), allocate another url for your api like /api/crossword
Your original idea of using session should not be used in this use case, especially with your Session.objects.all().delete() line (don't delete all session data without checking).

Django - Ajax without JQuery lib

I am Learning and using Ajax without jQuery Lib. I created a simple view which renders a random number on to the template. I added a button and called the ajax function. However, clicking the button doesn't change the value on the screen. I checked in DOM (firebug) and it shows the someText.responseText is yielding the whole html rather than just the value, however it has the new value in that HTML. I am sharing this to provide more information on what I have found so far. I am new to this and experimented it with a lot for ex; I have checked "request.is_ajax():" but somehow the view does not find ajax in request. I have printed request on command line and the GET querydict is empty.
Obviously I am not doing something in the correct manner for Django. Please assist.
I have a view;
def home(request):
rand_num = random.randint(1,100)
return render(request, 'home.html', {'rand_num':rand_num})
and html and script;
<html>
<head>
<script type='text/javascript'>
var someText;
function helloWorld(){
someText = new XMLHttpRequest();
someText.onreadystatechange = callBack;
someText.open("GET", "{% url 'home' %}", true);
someText.send();
};
// When information comes back from the server.
function callBack(){
if(someText.readyState==4 && someText.status==200){
document.getElementById('result').innerHtml = someText.responseText;
}
};
</script>
</head>
<body>
<div id="result">{{rand_num}}</div>
<input type='button' value='Abraca dabra!' onclick="helloWorld()"/>
</body>
</html>
here is the url for this view;
url(r'^$', 'socialauth.views.home', name='home'),
I am learning this from an online tutorial.
That is because your AJAX endpoint is the whole view - I.e. your AJAX request asks for the whole rendered template.
What you want is just a number, so make a new view and URL to return just the number, and make the AJAX request to that.
AJAX isn't anything special, its just a way to make an asynchronous request to a URL and get the contents returned.
For reference, a view using something like JSONResponse:
from django.http import JsonResponse
def get_random_number_json(request):
random_no = random.randint(1,100)
return JsonResponse({'random_no': random_no})
Then in your frontend Javascript, fetch url for that view, which will give you only the JSON in your javascript variable via your AJAX call, and instead of all that document.getElementById('result') processing, you can just grab the variable from the json object.

Flask with Javascript

I have been developing a webserver application using Flask. So far, I created a small framework, where the users can draw some boxes in a image, using canvas and javascript. I keep the boxes information in a vector in javascript as well as the image information. However, all this data must be submitted and stored in a database the server side. Therefore, I have a button to submit all this content, but I have no idea how to retrieve the javascript data I have, i.e.: boxes and image information.
Is it possible to get the javascript information to submit like that? I have come up with some ideas such as printing the information in hidden HTML elements, or, maybe, using AJAX for sending the information to the server, but I don't think those are the "correct" methods for dealing with this problem in Flask. So, does anyone have a idea. Here follow part of my code that may seem relevant for understanding my problem:
Models.py: My classes here are a little different: Blindmap=Image, Label=boxes. My database is modelled using SQLAlchemy.
blindmap_label = db.Table('blindmap_label',
db.Column('blindmap_id', db.Integer, db.ForeignKey('blindmap.id', ondelete = 'cascade'), primary_key = True),
db.Column('label_id', db.Integer, db.ForeignKey('label.id', ondelete = 'cascade'), primary_key = True))
class Blindmap(db.Model):
__tablename__ = 'blindmap'
id = db.Column(db.Integer, primary_key = True)
description = db.Column(db.String(50))
image = db.Column(db.String)
labels = db.relationship('Label', secondary = blindmap_label, backref = 'blindmaps', lazy = 'dynamic')
def __init__(self, label = None, **kwargs):
if label is None:
label = []
super(Blindmap, self).__init__(**kwargs)
def add_label(self, label):
if label not in self.labels:
self.labels.append(label)
db.session.commit()
def __repr__(self):
return '<Blindmap %r:>' % (self.id)
class Label(db.Model):
__tablename__ = 'label'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(50))
x = db.Column(db.Integer)
y = db.Column(db.Integer)
w = db.Column(db.Integer)
h = db.Column(db.Integer)
def __repr__(self):
return '<Pair %r:>' % (self.id)
My controllers information:
#app.route('/')
#app.route('/index')
def index():
blindmaps = db.session.query(Blindmap).all()
return render_template("index.html",
title = 'Home',
blindmaps = blindmaps)
#app.route('/new', methods = ['GET', 'POST'])
def new():
form = BlindmapForm()
if request.method=="POST":
if form.validate_on_submit():
blindmap = Blindmap(description=form.description.data)
redirect(url_for('index'))
return render_template("new.html",
title = 'New Blindmap',
form=form)
Try jQuery ajax:
function upload() {
// Generate the image data
var img= document.getElementById("myCanvas").toDataURL("image/png");
img = img.replace(/^data:image\/(png|jpg);base64,/, "")
// Sending the image data to Server
$.ajax({
type: 'POST',
url: '/upload', // /new
data: '{ "imageData" : "' + img + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
// On success code
}
});
}
Rest is get uploaded image data at server side using request.json['imageData'] and store it in database.
img = request.json['imageData'] # Store this in DB (use blob)
What you have to do is to use AJAX, the technique to "asynchronously" send requests and get responses from a server after the page is loaded on the client's browser, using JavaScript.
AJAX, in fact, stands for Asynchronous JavaScript And XML (even though it doesn't necessarily have to be neither completely asynchronous, nor you must resort to XML as a data exchange format). This is the standard way to access Web APIs, such as the one you crafted with Flask by exposing the ability to retrieve and persiste objects in your backend through URLs (the ones represented the the routes).
Modern browsers consistently expose the XMLHttpRequest constructor (MDN documentation) that can be used to create objects that allow the page to communicate with your Web server once it's loaded.
To improve cross-browser compatibility and code maintainability, you can resort to JavaScript frameworks that "wrap" the XMLHttpRequest with their own abstractions. I've been productively using jQuery for years for this purpose. In particular, in your case you would need the jQuery.ajax method (or, for POST operations, it's shorthand jQuery.post).
However I'll give you a small example of how to perform such request using vanilla JS so that you can understand what's going on in the browser even when using a framework:
// Create an instance of the XHR object
var postNewObject = new XMLHttpRequest();
// Define what the object is supposed to do once the server responds
postNewObject.onload = function () {
alert('Object saved!');
};
// Define the method (post), endpoint (/new) and whether the request
// should be async (i.e. the script continues after the send method
// and the onload method will be fired when the response arrives)
postNewObject.open("post", "/new", true);
// Send!
postNewObject.send(/* Here you should include the form data to post */);
// Since we set the request to be asynchronous, the script
// will continue to be executed and this alert will popup
// before the response arrives
alert('Saving...');
Refer to MDN for more details about using the XMLHttpRequest.

Categories

Resources