Adding a context variable with AJAX in Flask - javascript

I have a select form that needs to be populated through AJAX. Consider this simple example:
templates/index.html
<!DOCTYPE html>
<html>
<body>
<select id="elements">
</select>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$.ajax({
url: '/get-something/5',
type: "GET",
dataType: "html",
success: function (msg) {
$('#elements').html(msg)
}
})
</script>
</body>
</html>
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/get-something/<int:n>')
def get_something(n):
result = ''
for i in xrange(n):
result += "<option value='%s'>%s</option>\n" % (i, i)
return result
if __name__ == '__main__':
app.run(debug=True)
That works just fine and is what I did. But, I was wondering if there exists another (better?) way.
For instance, I'd prefer having a context variable to better separate the view from the controller. Something like this:
app.modified.py
#app.route('/get-something/<int:n>')
def get_something(n):
return dict(elements=xrange(n))
templates/index.modified.html
<select id="elements">
{% for elem in elements %}
<option value='{{ elem }}'>{{ elem }}</option>\n
{% endfor %}
</select>
Unfortunately, that does not work. It says, 'dict' object is not callable.
Any help please? Is this even possible? Notice that I don't want to reload the page, I want the same behavior that you get in the AJAX example.

Using index.modified, you need to do something like this:
return render_template('index.modified.html',
elements=your_dictionary)
Not trying to return a dictionary (which is why you are getting that error). See http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ii-templates fore more examples

You should be returning render_template('index.modified.html', elements=xrange(n)) since you want the html.
render_template returns a string which you can then encode as JSON. Ex:
data = render_template('index.modified.html', elements=xrange(n))
return json.dumps({'data': data})

Related

linking JavaScript code to Django database upon clicking on a button

I'm asked to work on a networking website that is like Twitter. I work with HTML,CSS, Javascript for the client-side and Django for the server-side. I'm trying to link between Javascript and Django using JSON and fetch as I want to create a button in each of the users' profile that upon being clicked by the registered user, it makes the registered follow the profile as it is saved in django database as a model containing the follower(follower) and the user followed(following) but upon clicking on follow button (in user.html) it doesn't save any data in the database
in models.py:
class follow(models.Model):
follower = models.ForeignKey("User",on_delete=models.CASCADE, related_name="follower")
following = models.ForeignKey("User",on_delete=models.CASCADE, related_name="following")
in user.html(contains the script):
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded',function(){
document.querySelectorAll('input').forEach(input =>{
input.addEventListener('click', function(){
console.log(input.id);
let follow_username = input.id
fetch('/follow/'+ follow_id, {
method:'PUT',
body: JSON.stringify({
follow: true
})
})
})
}
)
});
</script>
</head>
<body>
<h2>{{x.username}}</h2>
<form>
{% csrf_token %}
<input type="submit" value="follow" name ="follow" id={{x.username}}>
</form>
</body>
</html>
in urls.py:
from django.urls import path
from . import views
urlpatterns = [
path("follow/<str:name>", views.Users, name="follow")
]
in views.py:
def Users(request, name):
x = User.objects.get(username = name)
if request.method == 'PUT':
data = json.loads(request.body)
if data.get('follow') is not None:
user = request.user
anotherr = User.objects.filter(username = name)
another = User.objects.get(username = anotherr).id
follow.objects.create(follower = user, following = another)
return render (request, "network/user.html",{"x":x})
upon clicking on the follow button that present in user.html, no data is created in the database. so what is the problem?
I'll throw my best guesses on what's happening.. Just some improper syntax and undefined variables
View
another / anotherr no, just use x you're already fetching the user at the top of the view
get_or_create will not allow you to have duplicates / follow someone twice (generally a good idea)
Prints are just debugging, remove after you know it's working
def Users(request, name):
x = User.objects.get(username=name)
if request.method == 'PUT':
print('we\'ve hit put')
data = json.loads(request.body)
if data.get('follow') is not None:
print('in follow')
# Note: [User Obj Itself]
# follower = request.user (is: <User Obj>)
# following = x (is: <User Obj>)
followObj, createdBool = follow.objects.get_or_create(follower=request.user, following=x)
print('followObj', followObj)
print('created?', createdBool)
print('past follow')
print('about to render')
return render (request, "network/user.html",{"x":x})
Template
Idk what follow_id is, just use input.id
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded',function(){
document.querySelectorAll('input').forEach(input =>{
input.addEventListener('click', function(){
// this should be true
console.log(input.id == '{{x.username}}');
console.log('Fetch Url:\t' + '/follow/'+ input.id);
fetch('/follow/'+ input.id, {
method:'PUT',
body: JSON.stringify({
follow: true
})
})
})
}
)
});
</script>
</head>
<body>
<h2>{{x.username}}</h2>
<form>
{% csrf_token %}
<input type="submit" value="follow" name ="follow" id={{x.username}}>
</form>
</body>
</html>
If these don't work, tell me what print or console.log got hit or didn't get hit- that'll really help narrow down the issue even more
Edit
Supposedly this, putting a token in a header, will work if you don't want to put a #csrf_exempt decorator (which might be a good idea tbh)
fetch('/follow/'+ input.id, {
method:'PUT',
headers: { 'X-CSRFToken': $('[name=csrfmiddlewaretoken]').val() },
body: JSON.stringify({
follow: true
})
})

how to pass js value to flask route

This is my list where i tried to get the value of the of a tag
{% extends 'base.html'%}
{% block body %}
<div onclick="pass()">
{{list1[1]}}
</div>
here i tried to get the value of a tag and have tried to pass info route
<script>
function pass() {
var a = document.getElementsByTagName('a');
var w = console.log(a[0].outerHTML);
window.location = "/info/" + w;
}
</script>
{% endblock %}
but show the following error
Not Found
http://127.0.0.1:5000/info/undefined
this is my info route
#app.route('/info', methods=['GET', 'POST'])
def info():
result = request.get_data
print(result)
return render_template('info.html', result=result)
why it's not displaying any data of within a tag
Thank you in Advance
window.location simply opens an HTML page. window.location = "/info/" + w; creates a route /info/w/ but you've only specified the route /info.
You need to send the a data to the server via a form and use Flask's request object to access it.

Access Django variable from JavaScript variable

First of all, I will like to say this is my first question here! (pardon me if this is redundant or duplicated)
I am having some problems with calling JS scripts from Django template:
{% for suggestion in suggestions %}
<img class="catalogue-poster" src="{{ suggestion.poster }}" alt="Portada" onclick="
document.getElementById('{{form.title.auto_id}}').value = '{{suggestion.title}}'
document.getElementById('{{form.year.auto_id}}').value = '{{suggestion.year}}'
document.getElementById('{{form.director.auto_id}}').value = '{{suggestion.director}}'
document.getElementById('{{form.rating.auto_id}}').value = '{{suggestion.rating}}'
document.getElementById('{{form.poster.auto_id}}').value = '{{suggestion.poster}}'
document.getElementById('{{form.trailer.auto_id}}').value = '{{suggestion.trailer}}'
document.getElementById('{{form.synopsis.auto_id}}').value = '{{suggestion.synopsis}}'
document.getElementById('{{form.cast.auto_id}}').value = '{{suggestion.cast}}'
" />
{% endfor %}
So, first of all, how can I declare a function outside. I'm a C developer, sorry for my ignorance.
I've tried to create a script outside, such as
<script>
function foo() {
console.log('Hey');
});
</script>
And invoke it this way:
<img class="catalogue-poster" src="{{ suggestion.poster }}" alt="Portada" onclick="foo()"/>
But this simple thing that works on pure HTML, with django templates does not seem to work...
On the other hand, the real question was, is there a way to access a Django variable passed in render with a js variable?
Such as:
const jsVariable = 'title';
document.getElementById('{{form.jsVariable.auto_id}}').value = '{{suggestion.jsVariable}}'
I have not found any way to accomplish this, maybe there is another great idea!
I have tried one example. where is send a variable from python script and access its value in JavaScript
1) In views.py
from django.shortcuts import render
def home_view(request):
var_name = 'hello'
return render(request, 'home.html', {'var_name':var_name})
2) In html file(home.html)
<html>
<h1>Home Page</h1>
<input type="button" value="Submit" onclick="fun()">
<script>
function fun(){
console.log('hello world '+ '{{var_name}}' );
}
var temp = '{{var_name}}';
console.log(temp + 20);
</script>
</html>
If i click submit button ( hello world hello ) is printed in console.
I stored value of var_name in temp which can be further used.
From your example, it looks you want to programmatically access a Django model's attribute in Javascript.
The main takeaway is that you first need to expose the data structure you want to access (i.e. the model) in Javascript.
Here's a simple, redacted, proof-of-concept you can try.
import json
def my_view(request):
obj = MyModel.objects.get(1)
obj_dict = {
"foo": obj.foo,
"bar": obj.bar,
}
return render(request, 'my_view.html', context={'obj_json': json.dumps(obj_dict)} )
<script>
var obj = {{obj_json}};
var field = 'foo';
console.log(obj[field]);
Check out Convert Django Model object to dict with all of the fields intact for a run-down on options to serialize Django models into dictionaries.
Well, finally I found a solution for both exposed problems.
First of all, the script function I declared was not working because it seems that there is an attribute called autocomplete (see autocomplete HTML attribute)
So, you can not declare a JavaScript function with this name, my fail.
Uncaught TypeError: autocomplete is not a function
Finally, the simple solution I found was passing an array of dicts to the template:
return render(request, 'example.html', {'form': form, 'suggestions': suggestions })
And then in the template:
{% for suggestion in suggestions %}
<img src="{{ suggestion.poster }}" onclick="autocompleteMovie({{suggestion}});" />
{% endfor %}
<script>
function autocompleteMovie(suggestion){
for (let field in suggestion)
document.getElementById('id_' + field).value = suggestion[field]
}
</script
Which, comparing it with the question, really simplifies the problem.

Passing array from Flask to Javascript to create options for drop down menu

I am new to Flask and Javascript. I am trying to upload a file and use one of its columns as options in the drop down menu. Please correct me where I am wrong.
Here are the codes:
Flask:
from flask import Flask, render_template, redirect, url_for, request, flash, send_from_directory
from werkzeug import secure_filename
import os
import pandas as pd
import numpy as np
import json
UPLOAD_FOLDER = 'uploads/'
ALLOWED_EXTENSIONS = set(['csv'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
#app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['data_file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
data = pd.read_csv(os.path.join(app.config['UPLOAD_FOLDER'], filename))
names = data['some_column']
return redirect(url_for('drop_down', names=names))
#return render_template('drop_down.html', names=names)
return render_template('file_upload.html')
#app.route('/meta')
def drop_down():
return render_template('drop_down.html')
Javascript:
function my_script(){
console.log('script called.');
//var cars = ["Volvo","Ferrari","Audi","BMW","Mercedes","Porche","Saab","Avanti"];
var cars = {{ names|safe }};
console.log('cars assigned.');
function make_drop_down(list_of_names, element_id){
select_elem = document.getElementById(element_id)
if(select_elem){
for(var i = 0; i < list_of_names.length; i++) {
var option = document.createElement('option');
option.innerHTML = list_of_names[i];
option.value = list_of_names[i];
select_elem.appendChild(option);
}
}
};
console.log("Making Drop Downs!!");
make_drop_down(cars, 'drop_down_1');
make_drop_down(cars, 'drop_down_2');
console.log("Made Drop Downs!!");
};
html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="static/drop_down.js"></script>
<title>DROP DOWN</title>
</head>
<body onload="my_script()">
<select id="drop_down_1">
<option>Choose Option 1</option>
</select>
</br></br>
<select id="drop_down_2">
<option>Choose Option 2</option>
</select>
</body>
</html>
I get the following error on the console:
ReferenceError: my_script is not defined
There are two problems.
The first one is that you are not passing the list of cars in your view handeling /meta
#app.route('/meta')
def drop_down():
return render_template('drop_down.html')
This should probably look something like this:
#app.route('/meta')
def drop_down():
cars = ["Volvo","Ferrari","Audi","BMW","Mercedes","Porche","Saab","Avanti"]
return render_template('drop_down.html',
names=cars)
The second problem is that your javascript won't be able to access the list, unless you pass it in your call to the function.
html
<body onload="my_script({{ names }})">
javascript
function my_script(names){
console.log('script called.');
var cars = names;
...
Edit:
The function that handles the view is the function that needs to pass the data. You could also use the commented away part of your upload file, which calls render_template... with the necessary data, but this doesn't feel as a "nice" approach.
You need to make the data available to your drop_down() view, either by storing it in a database, reading the data from the file in this function or by storing it in the session. So that you can pass the data along with the template

Ajax JSON response not working

I am trying to fetch JSON response from my Django App but response is not working :
Here is my views.py :
import json
import traceback
from django.http import HttpResponse
from django.template import Context,loader
from django.template import RequestContext
from django.shortcuts import render_to_response
from eScraperInterfaceApp.eScraperUtils import eScraperUtils
#------------------------------------------------------------------------------
def renderError(message):
"""
This function displays error message
"""
t = loader.get_template("error.html")
c = Context({ 'Message':message})
return HttpResponse(t.render(c))
def index(request,template = 'index.html',
page_template = 'index_page.html' ):
"""
This function handles request for index page
"""
try:
context = {}
contextList = []
utilsOBJ = eScraperUtils()
q = {"size" : 300000,
"query" :{ "match_all" : { "boost" : 1.2 }}}
results = utilsOBJ.search(q)
for i in results['hits']['hits']:
contextDict = i['_source']
contextDict['image_paths'] = json.loads(contextDict['image_paths'])
contextList.append(contextDict)
context.update({'contextList':contextList,'page_template': page_template})
if request.is_ajax(): # override the template and use the 'page' style instead.
template = page_template
return render_to_response(
template, context, context_instance=RequestContext(request) )
except :
return renderError('%s' % (traceback.format_exc()))
def search (request,template = 'index.html',
page_template = 'index_page.html' ):
try:
if request.method == 'POST':
context = {}
contextList = []
keyWord = request.POST['keyWord']
print keyWord
utilsOBJ = eScraperUtils()
results = utilsOBJ.search('productCategory:%(keyWord)s or productSubCategory:%(keyWord)s or productDesc:%(keyWord)s' % {'keyWord' : keyWord})
for i in results['hits']['hits']:
contextDict = i['_source']
contextDict['image_paths'] = json.loads(contextDict['image_paths'])
contextList.append(contextDict)
context.update({'contextList':contextList,'page_template': page_template})
if request.is_ajax(): # override the template and use the 'page' style instead.
template = page_template
return HttpResponse(template, json.dumps(context), context_instance=RequestContext(request),
content_type="application/json")
except :
return renderError('%s' % (traceback.format_exc()))
#------------------------------------------------------------------------------
index.html :
<html>
<head>
<title>Fashion</title>
<link rel="stylesheet" type="text/css" href="static/css/style.css">
</head>
<body>
<form action="">
{% csrf_token %}
<input id="query" type="text" />
<input id="search-submit" type="button" value="Search" />
</form>
<div class="product_container">
<ul class="product_list">
<div class="endless_page_template">
{% include page_template %}
</div>
</ul>
</div>
<div class="product_container">
<ul class="product_list">
<div class="endless_page_template">
{% include page_template %}
</div>
</ul>
</div>
{% block js %}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="static/js/endless_on_scroll.js"></script>
<script src="static/js/endless-pagination.js"></script>
<script>
$.endlessPaginate({paginateOnScroll: true,
endless_on_scroll_margin : 10,
paginateOnScrollChunkSize: 5
});</script>
<script type="text/javascript">
$("#search-submit").click(function() {
// Get the query string from the text field
var query = $("#query").val();
alert(query);
data = { 'csrfmiddlewaretoken': '{{ csrf_token }}', 'keyWord' : query};
// Retrieve a page from the server and insert its contents
// into the selected document.
$.ajax({
type: "POST",
url: '/search/',
data: data,
success: function(context,status){
alert("Data: " + context + "Status: " + status);
},
error: function( error ){
alert( error );
},
contentType: "application/json; charset=utf-8",
dataType: 'json',
});
});
</script>
{% endblock %}
</body>
</html>
index_page.html :
{% load endless %}
{% paginate 10 contextList %}
{% for item in contextList %}
<li >
<a href="{{ item.productURL }}" ><img src="/images/{{ item.image_paths.0 }}/" height="100" width="100" border='1px solid'/></a>
<br>
<span class="price">
<span class="mrp">MRP : {{ item.productMRP}}</span>
{% if item.productPrice %}<br>
<span class="discounted_price">Offer Price : {{ item.productPrice}}</span>
{%endif%}
</span>
</li>
{% endfor %}
{% show_more "even more" "working" %}
What i want is to fetch the server response and update the contextList .... But it is not working....
The problem you're facing is that you're trying to update a Django template compiled variable called context_list this won't happen magically by using AJAX since Django has precompiled the HTML you're serving when you hit the page initially.
You can't circumvent this but you can work around it and below I'll show you two ways of doing it.
Your success() handler in your jQuery script that you have that manages the search gets the newly HTML that you've recompiled but you're not using it anywhere ergo, it won't work.
In this case you're just logging some stuff out to console. (This would be where you're using option #2.)
You have two options as I see it. (It's a lot of code so I'll give you the pointers and not the implementation, won't strip you of all the fun!)
I'll give you a quick run down of both and then you can decide which way you want to take.
You can use jQuerys $.load() method in order to fetch a
recompiled template.
You can use $.getJSON() and get the
objects in JSON format and then update the HTML accordingly.
First option - $.load()
#Django
def search_view(keyword, request):
search_result = SearchModel.objects.filter(some_field=keyword)
t = loader.get_template("some_result_template.html")
c = Context({'search_results':search_result})
return render(t.render(c))
#jQuery
$("#result").load("url_to_your_search", { 'keyword': 'search_me' } );
Second option - $.getJSON()
#Django
from django.core import serializers
def search_view(keyword, request):
search_result = SearchModel.objects.filter(some_field=keyword)
json_data = serializers.serialize('json', search_result)
return HttpResponse(json_data, mimetype='application/json')
#jQuery
$.getJSON('url_to_your_search_view', { keyword: "search_me" }, function(json_data) {
var items = [];
$.each(json_data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
Now the JSON code is taken straight from the docs, so you would have to modify it but you get the gist of what's needed in order for yours to work.

Categories

Resources