Make API call on page load (Django) - django

I'm building a basic Django site.
Currently, I'm trying figure out a way to make an API call and retrieve the results on page load.
Is it possible to use the js .onload function to call a Django view function?
Any suggestions/tips would be appreciated!

you can use "requests" library and making a request on the django view for this page.
import requests
def my_view(request):
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
context = {
'data': r.json()
}
return render(request, 'my_html.html', context)

You can simply use JavaScript fetch API like following:
page.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Title</title>
</head>
<body>
<h1 id="msg"></h1>
<script>
var url = 'http://127.0.0.1:8080/message';
fetch(url).then(
response => response.json()
).then(function(data) {
document.getElementById("msg").textContent = data['message'];
});
</script>
</body>
</html>
views.html
from django.shortcuts import render
from django.http import JsonResponse
def index(request):
return render(request, "index.html")
def message(request):
return JsonResponse({"message": "Hello World!"})

Related

TemplateDoesNotExist at /test/ error popped up while running application

I am using Django 3.0.8 My view function is as follows:
from django.shortcuts import render import datetime
# Create your views here.
def date_time_view(request):
date=datetime.datetime.now()
h=int(date.strftime('%H'))
if h<12:
msg='Hello Guest!!! Very good Morning!!!'
elif h<16:
msg='Hello Guest!!! Very good Afternoon !!!'
elif h<21:
msg='Hello Guest!!! Very good Evening!!!'
else:
msg='HELLO GUEST!! very good Night!!!'
my_dict = {'date':date,'msg':msg}
return render(request, 'testapp/results.html', my_dict)
and my template is as follows:
<!DOCTYPE html> {%load staticfiles%}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>hello</title>
</head>
<body>
<h1>{{msg}}</h1>
<h2>{{date}}</h2>
<img src="{%static " images/images.jpg" %}">
</body>
</html>
Check your configuration in your project settings file.
Templates can reside in each app separately, but also in a templates folder in APPS_DIR (folder with all Django apps).
Here is official docs for Django 3 templates:
https://docs.djangoproject.com/en/3.0/topics/templates/
Check your template's location. It should be yourproject/yourapp/templates/testapp.

unable to use the variable in django

i recently started my django course online nad getting some problem.
i am not able to use my variable which i passed from index.html to about.html.
but in about.html it is not shown up.
.py file code :
from django .http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request , 'index.html')
def about(request):
t1 = print(request.GET.get('text' , 'default'))
return render(request , 'about.html' , t1)
index.html file code:
<!DOCTYPE html>
<html>
<head>
<title>template</title>
</head>
<body>
<h1> hello everyone </h1>
<form action="/about" , method="get">
<textarea name="text" style="margin: 0px; width: 1245px; height: 171px;"></textarea>
<input type="submit" name="OK">
</form>
</body>
</html>
about.html file code :
<!DOCTYPE html>
<html>
<head>
<title>template</title>
</head>
<body>
<h1>you typed {{t1}}</h1>
</form>
</body>
</html>
print(..) does not return anything. You can pass the variable to the context, for example:
def about(request):
return render(
request ,
'about.html' ,
{'t1': request.GET.get('text' , 'default')}
)

Flask: Work around a timeout error while running long data collection process

I have a Flask app that will run on OpenShift, that takes a while to generate data and can lead to a timeout error.
From looking at examples, I thought that I could render a "please wait" template which returns immediately, while also calling my long running, run_analysis() function. When the data was finished being collected, run_analysis() would render a new page.
Either this isn't possible or I'm doing it wrong. Thanks for your help.
from flask import Flask
import jinja2
app = Flask(__name__)
please_wait_template = jinja2.Template('''
<!DOCTYPE html>
<html lang="en">
<head>
<title>please wait for data</title>
<meta charset="UTF-8">
</head>
<body>
<h1>Collecting data, this could take a while.</h1>
</body>
</html>''')
input_template = jinja2.Template('''
<!DOCTYPE html>
<html lang="en">
<head>
<title>Input Keywords</title>
<meta charset="UTF-8">
</head>
<body>
<h1>Doing stuff</h1>
<form action="/please_wait/" method="POST">
Enter keywords<br>
<input type="text" name="kw" placeholder="data science"><br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>''')
output_template = jinja2.Template("""
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>results</title>
<meta charset="UTF-8">
</head>
<body>
<h1>RESULTS</h1>
{{ results }}
</body>
</html>
""")
#app.route('/')
def render_input_page():
return input_template.render()
#app.route('/please_wait/')
def please_wait():
return please_wait_template.render()
#app.route('/please_wait/', methods=['post'])
def run_analysis():
kws = request.form['kw']
zips = request.form['zipcodes']
template = run_long_analysis(kws, zips)
return template
def run_long_analysis(kws, zips):
import time
time.sleep(2400)
return output_template(results="testing")
Yes, it is possible. You will want to break out of the single file however. i.e. creating a templates directory and storing your templates there. http://flask.pocoo.org/docs/0.10/quickstart/#rendering-templates
Quoting the docs basic example:
from flask import render_template
#app.route('/hello/')
#app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
You can see render_template is used instead of the .render() or output_template. This is convenient and it makes reading the Flask logic easier.
Specifically to your code:
#app.route('/please_wait/', methods=['post'])
def run_analysis():
kws = request.form['kw']
zips = request.form['zipcodes']
template = run_long_analysis(kws, zips)
The line zips = request.form['zipcodes'] would be troublesome, because I don't see a form under the please_wait route. Perhaps you realize that though.
In general, a tool that will help in situations like this, in my experience is the Flask session object. Which is basically a global dictionary that persists across a user session. See more here in the docs http://flask.pocoo.org/docs/0.10/quickstart/#sessions.
Quoting that example:
from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
#app.route('/')
def index():
if 'username' in session:
return 'Logged in as %s' % escape(session['username'])
return 'You are not logged in'
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form action="" method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''
#app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('index'))
# set the secret key. keep this really secret:
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
You can see in the above example that the session object behaves like a dict. It also allows you to dynamically change content displayed, via Jinja2. In other words, it can be passed into the template. These methods in conjunction, should give you the functionality you are looking for.

Dynamic programing in django not working properly

In django, tried to create a dynamic web page with ajax. But it doesn't takes the automatic reload. The requesting to the server is only done when reloading the page. Here my codes.
How i make into dynamic reloading.
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from random import randrange
def main(request):
return render(request, 'index.html')
def random_generator(request):
return HttpResponse(randrange(0, 100))
urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
url('^main/$', 'Signup.views.main'),
url('^random/$', 'Signup.views.random_generator')
)
random.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function refreshRandom() {
$.ajax({
url: '/random/',
dataType: 'html',
success: function(data) {
$('#random').html(data);
},
complete: function() {
window.setTimeout(refreshRandom, 1000);
}
});
}
window.setTimeout(refreshRandom, 1000);
</script>
</head>
<body>
<div id='random'></div>
</body>
</html>
You can use Jquery like this
$(document).ready(function() {
// JQuery code to be added in here.
});
in your template use
<script src="{% static "/js/jquery.js" %}"></script>
<script src="{% static "/js/rango-ajax.js" %}"></script>

Why is django not showing the content what I declare in template?

I have the following in the templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Rango</title>
</head>
<body>
<h1>Rango says...</h1>
hello world! <strong>foo</strong><br />
About<br />
</body>
How ever, the output is the following (page source)
<Text Node: '<!DOCTYPE html>
<html>
'>
What could be the reason?
EDIT:
Here is my view code:
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader
# Create your views here.
def index(request):
template = loader.get_template('index.html')
return HttpResponse(template)
You need to render the template in the view.
Try the render_to_response shortcut.
Otherwise show us the view code.