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.
Related
It is exactly how it sounds. My main goal is to make the css file work with django template so I can design my templates.
Yesterday I tried and initially my folder structure was wrong. I placed static folder in myapp folder. Didn't work. I tried putting it in templates folder. It only worked when I had 2 static folders both in myapp and templates folder. Realized it isn't a working solution.
I placed a single static folder with a css file in it in mysite folder, at the same level with myapp folder and everything seemed to work. Satisfied I left at that.
Today I came back to it and it stopped working. It seems to be frozen. Not responding to the new codes. Old colors are showing but new colors aren't, which is odd. Tried changing the old colors, it won't change. Literally my css file has a class name .intro where I changed the color from purple to red, my template still showing purple which I set yesterday.
My template shows no error and all the texts and divs I am adding are updating with no issue.Kind of lost where I may have gone wrong. Certainly don't want to work with 2/3 same css file and static folder if I can help it.
Here are some codes.
My folder structure-
Everytime I update the css and refresh the template my console is showing some kind of error, here they are-
Settings.py file seems correct. Here is the relevant part-
import os
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
...
...
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
)
STATIC_ROOT= os.path.join(BASE_DIR, 'staticfiles')
my base.html -
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="{% static 'ok.css' %}"/>
</head>
<body>
{% block content %}
<h2 class="ok">This is a test</h2>
<div class="solved">This took a while!</div>
<div class="container">Didn't work on the other site!</div>
{% endblock content %}
</body>
</html>
and test.html -
{% extends "myapp/base.html" %}
{% block content %}
<h2 class="again">Content for My App</h2>
<p class="intro">Stuff etc etc.</p>
<p class="ok">write some more</p>
<div class="container">This should work</div>
{% endblock %}
URLs.py even though I think I am doing ok there -
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('base/', views.ok, name='base'),
path('test/', views.test, name='test')
]
And finally views.py , another page I don't think have any issues -
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
context = {}
return render(request, 'myapp/index.html')
def ok(request):
return render(request, 'myapp/base.html')
def test(request):
return render(request, 'myapp/test.html')
If you can spot anything kindly let me know. Any help is appreciated. Thanks.
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!"})
I'm trying to embed a bokeh plot into a template (home.html), but nothing is displayed after executing the code.
here's the code.
views.py (all packages are imported)
def home(request):
s = [1,4,6,8]
h = [1,5,9,8]
p = figure(plot_width=600, plot_height=600)
p.vbar(x=s, width=0.5, bottom=0,
top=h, color="black")
script, div = components(p, CDN)
return render(request, 'home.html', {'div': div, 'script': script})
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Experiment with Bokeh</title>
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.js"></script>
<link rel="stylesheet" href="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.css">
</head>
<body>
<h1>hello</h1>
{{ div|safe }}
{{ script|safe }}
</body>
</html>
it displays nothing at the end, there's no error message, but and the page is completely blank
Help, Please!!
You are loading an ancient version of BokehJS from CDN:
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.js"></script>
<link rel="stylesheet" href="http://cdn.bokeh.org/bokeh/release/bokeh-0.8.1.min.css">
The 0.8.1 release is now several years old. By contrast, the vbar glyph method that you are using was only added quite recently. You need to make sure that the version of the BokehJS resources that you load in your template actually match the version of the Bokeh library that you are using.
I am using linux and created a Django project.
I have folder in my home directory /home/simha/siteimages
i am trying to show a list of images from the above directory
In views.py
def gallery(request):
path="/home/simha/siteimages"
img_list =os.listdir(path)
return render(request,'blog/gallery.html', {'images': img_list})
gallery.html is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for image in images %}
<img src='/static/{{image}}' />
{% endfor %}
</body>
</html>
Its not working.
It says at img_list =os.listdir(path) error No such file or directory
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.