I'm so confused. The thing worked fine last night and all of a sudden today stopped working.
The purpose of this page is to generate a list of colors. The templates are located in their own folder called "templates", but GAE can't seem to find these templates at all.
What am I doing wrong here?
main2.py:
import bottle
from bottle import static_file
from google.appengine.ext.webapp import util
from bottle import route
# Load the template system
from jinja2 import Environment, FileSystemLoader
# Indicate from where the templates will be loaded
env = Environment(loader=FileSystemLoader('./templates/'))
# for randomly picking colors
import random
colors = 'green red blue';
#route('/favicon.ico')
def send_image():
filename = 'favicon.ico'
return static_file(filename, root='./images/', mimetype='image/ico');
#route('/hello')
def hello():
template = env.get_template('home.html');
color_list = colors.split();
num_colors = random.randint(0,len(color_list)+1);
color_list = color_list[:num_colors];
return template.render(title="Color List Page!", color_list=color_list);
util.run_wsgi_app(bottle.default_app())
app.yaml
application: yao-webapp2
version: 1
api_version: 1
runtime: python
handlers:
- url: .*
script: main2.py
/templates/base.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
{% block title %}
I am stupid as heck: I forgot to fill in a title.
{% endblock %}
</title>
</head>
<body>
{% block content %}
No body knows the trouble I've seen.
{% endblock %}
</body>
</html>
/templates/home.html
{% extends "base.html" %}
{% block title %}
{{page_title}}
{% endblock %}
{% block content %}
<h1>Some Colors I know </h1>
<p>I have a list of colors that I know</p>
{% if color_list %}
<ul>
{% for color in color_list %}
<li> {{ color }} </li>
{% endfor %}
</ul>
{% else %}
<p>Oops! No colors.</p>
{% endif %}
{% endblock %}
not sure what error you are getting but i would try to use absolute paths.
instead of
env = Environment(loader=FileSystemLoader('./templates/'))
try to use this code:
templatespath = os.path.join(os.path.dirname(__file__), "templates")
env = Environment(loader=FileSystemLoader(templatespath))
Related
OK
So you didn't like my last question
Here is a SECOND question, with much more information than actually needed. It's a very simple problem defining the base dir inside the flask-bootstrap module. If you managed to see my last question, I showed my code, but here is some more of the USELESS information you wanted for some odd reason:
Index.html
{% extends 'bootstrap/base.html' %}
<!-- TEST THINGS ON A DIFFERENT REPL! -->
<!DOCTYPE html>
<html>
<head>
<!-- This is for the tab -->
<title>Helliott-chip</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="{{ url_for('static', filename='style.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
<!-- Title on top -->
<h1><center>Helliot-Chip</center></h1>
<p>New User? Click to Register!</p>
<!-- Grey Menu Select -->
<div class="scrollmenu1">
{% if current_user.is_anonymous %}
Login
{% else %}
Logout
Profile
{% endif %}
Home
About
Explore
Videos
Music
</div>
{% block content %}
<h1>Hi, {{ current_user.username }}!</h1>
{% endblock %}
{% block app_content %}{% endblock %}
{% block scripts %}
{{ super() }}
{{ moment.include_moment() }}
{% endblock %}
</body>
</html>
init.py
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from config import Config
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_moment import Moment
app = Flask(__name__)
Bootstrap(app)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
mail = Mail(app)
moment = Moment(app)
from app import models, errors
So now that I have that down, my error (after I changed the index to base in the index.html):
[2021-04-13 17:18:39,365] INFO in debughelpers: Locating template "index.html":
1: trying loader of application "app"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /home/runner/Website30/app/templates
-> found ('/home/runner/Website30/app/templates/index.html')
2: trying loader of blueprint "bootstrap" (flask_bootstrap)
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /opt/virtualenvs/python3/lib/python3.8/site-packages/flask_bootstrap/templates
-> no match
[2021-04-13 17:18:39,372] INFO in debughelpers: Locating template "bootstrap/base.html":
1: trying loader of application "app"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /home/runner/Website30/app/templates
-> no match
2: trying loader of blueprint "bootstrap" (flask_bootstrap)
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /opt/virtualenvs/python3/lib/python3.8/site-packages/flask_bootstrap/templates
-> found ('/opt/virtualenvs/python3/lib/python3.8/site-packages/flask_bootstrap/templates/bootstrap/base.html')
172.18.0.1 - - [13/Apr/2021 17:18:39] "GET / HTTP/1.1" 200 -
[2021-04-13 17:18:40,173] INFO in debughelpers: Locating template "404.html":
1: trying loader of application "app"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /home/runner/Website30/app/templates
-> found ('/home/runner/Website30/app/templates/404.html')
2: trying loader of blueprint "bootstrap" (flask_bootstrap)
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /opt/virtualenvs/python3/lib/python3.8/site-packages/flask_bootstrap/templates
-> no match
And my error before I changed it:
jinja2.exceptions.TemplateNotFound: bootstrap/index.html
Now this time without having my question being shut down from any answers in general (which I may note is opposing the purpose of this site) What would be wrong here? Is something wrong with the way I'm initializing flask-bootstrap, or is there some command I need to put in the terminal? Feel free to ask questions, and thanks a lot if it's a simple problem I'm missing. And I apologize for any unneeded attitude, I was just disappointed in the person who locked my last question for "not enough information".
There is an issue with the way you are initializing flask-bootstrap. This how you should go about it:
# Your previous imports
from flask_bootstrap import Bootstrap
app = Flask(__name__)
bootstrap = Bootstrap(app)
# ...
Basically, update the line:
Bootstrap(app)
to:
bootstrap = Bootstrap(app)
This is exactly what you have done for the other installed packages too.
Maintain the line {% extends 'bootstrap/base.html' %} in your base template (which is the parent template). Do not change it to {% extends 'bootstrap/index.html' %} This file inherits the styles, layout, features etc from bootstrap's base template.
<!-- base.html -->
{% extends 'bootstrap/base.html' %}
{% block head %}
<!-- Head information goes here -->
{% endblock %}
{% block navbar %}
<!-- Your navbar goes here -->
{% endblock %}
{% block content %}
<!-- flash message goes here -->
{% block app_content %}
<!-- Content from your custom HTML templates will go here -->
{% endblock %}
{% endblock %}
{% block scripts %}
<!-- Your scripts go here -->
{% endblock %}
In your index.html file which inherits your base,html, you will do:
<!-- index.html -->
{% extends 'base.html' %}
{% block app_content %}
<!-- Content goes here -->
{% endblock %}
Need some help, not getting the content from the database not sure why this is happening
using python flask,sqlalchemy with a small sqlite database
I need to see the content from the database displayed on the web page.
At the moment I see only the Home link which is static in the template file.
app.py contains a part of this
#app.route('/page/<int:page_id>')
def view_page(page_id):
page = db.session.query(Pages).filter_by(id=page_id).first()
return render_template('page.html', id=page.id, title=page.title.decode(),
content=page.content.decode())
page.html (this is the template)
{% extends "master.html" %}
{% block content %}
<!DOCTYPE html>
{% for page in pages %}
<h3>{{ page.title.decode() |truncate(150)}}
</h3></a>
<p>{{ page.content.decode() |safe | truncate(350) }}</p>
{% endfor %}
Home
{% endblock %}
</html>
You have to send model with your return template.
#app.route('/page/<int:page_id>')
def view_page(page_id):
pages = Pages.query.all()
return render_template('page.html', pages=pages)
So I am half way through a tutorial useing the book Tango With Django trying desperately hard to take on as much information as i can about Django.
Now i am trying to set up a template that lists all the category's but i get an error
invalid syntax (rango_template_tags.py, line 8)
I have no idea why i am getting this line, absolutely none i have checked it with the book 5 + times but i cant find anything that looks out of place of wrong. Can anyone please tell me why i am getting this error.
Base.html
{% load rango_template_tags %}
<div>
{% block sidebar_block %}
{% get_category_list %}
{% endblock %}
</div>
# This file has more within it these are the new pieces of code that break the template system. If these are in it wont work.
rango_template_tags
from django import template
from rango.models import Category
register = template.Library()
#register.inclusion_tag('rango/cats.html')
def get_category_list():
return {'cats' Category.objects.all()}
cats.html
<ul>
{% if cats %}
{% for c in cats %}
<li>{{ c.name }}</li>
{% endfor %}
{% else %}
<li><strong> There ar eno categories presen. </strong></li>
{% endif %}
</ul>
In python dictionary, each key is separated from its value by a colon (:)
Change your return statement from {'cats' Category.objects.all()} to {'cats': Category.objects.all()} and code within function or block should be idented.
from django import template
from rango.models import Category
register = template.Library()
#register.inclusion_tag('rango/cats.html')
def get_category_list():
return {'cats': Category.objects.all()}
I have a static homepage, but I'm also using the i18n subsites plugin. So for the homepage I have, in pelicanconf.py:
INDEX_SAVE_AS = 'blog/index.html'
INDEX_URL = 'blog'
and for the English version:
I18N_SUBSITES = {
'en': {
'OUTPUT_PATH': 'output/en/',
'INDEX_SAVE_AS': 'blog/index.html',
'INDEX_URL': 'blog',
}
}
(truncated unnecessary bits)
The problem lies with the translation link for the homepage. The translations macro has:
{% for translation in article.translations %}
{{ translation.lang | lookup_lang_name }}
So for the English-language homepage I could either set the url and output filename as:
<meta name="save_as" content="en/index.html">
<meta name="url" content="en/">
Which makes the translation link go to site.com/en/en/ (and works), or set them as:
<meta name="save_as" content="index.html">
<meta name="url" content="/">
Which conflicts with the standard-language homepage.
Another, related problem is that the index page (blog page) has no translation link to the English or back to the standard-language version whatsoever.
What can I do to solve this?
I was able to solve my problem with the following translations macro:
{% macro translations_for(article) %}
{% if extra_siteurls %}
{% for lang, url in extra_siteurls.items() %}
{% if article %}
{{ lang | lookup_lang_name }}
{% else %}
{{ lang | lookup_lang_name }}
{% endif %}
{% endfor %}
{% endif %}
{% endmacro %}
And by adding a permalink option the each article and page I can also translate the URL for said article or page (otherwise you could just use slug in the above macro).
Last but not least I also removed the url and save_as data from both homepages.
To fix the blog page, I added this to the index.html template:
{% block translation_links %}
{% if lang == 'nl' %}
English
{% else %}
Nederlands
{% endif %}
{% endblock %}
For the second part of your question, have a look at creating language buttons
I have a string that looks like
string '''
<html>
<head>
{% block head %}{% endblock %}
... other stuff ...
</head>
<body>
{% block body %}{% endblock %}
... other stuff ...
</body>
</html>
'''
I would like the following django template to inherit from the above string:
{% block head %}
... other stuff ...
{% endblock %}
{% block body %}
<h1>Other stuff</h1>
{% endblock %}
Since the string is not in a file a can't just specify it's filename to the template rendering engine. Any ideas?
In order to implement string-only template extender, you would probably have to implement your template loader. Actually, a much cleaner solution is to use threed's suggestion below. Pass a parent Template() in the context rather than the name of disk template:
>>> from django.template import Context, Template
>>> extend_me = Template("Before A. {% block a %}{% endblock %}. After A")
>>> str_template = "{% extends parent %} {% block a %}This is inside A{% endblock %}"
>>> Template(str_template).render(Context({"parent": extend_me}))
u'Before A. This is inside A. After A'
Unfortunately this doesn't seem to work on django 1.3, possibly due to bug #7377 (you can't use the extends and block tags in string templates). Though it does work fine in 1.2. So if you happen to be running 1.3, you can look up the history of this question and use my hack :)
The extends template tag allows you to specify a variable name (since ver 1.0).
There's an example of it's usage in this question: How do I use Django's template extends variable?
It turns out there's an even simpler way to achieve this:
from google.appengine.ext.webapp import template
parent = template.Template("<html><body>{% block content %}{% endblock %}</body></html>")
path = os.path.join(os.path.dirname(__file__), 'index.html')
template.render(path, template.Context({"baseTemplate": parent}))
Where the index.html file looks like this:
{% extends baseTemplate %}
{% block content %}
<h1>Hello World!</h1>
{% endblock %}
In this case, the template object (as opposed to just a string) is passed into the context of the child template and used as the variable in the 'extends' tag.