I have a function in python that displays a list of names.
def search():
with open('business_ten.json') as f:
data=f.read()
jsondata=json.loads(data)
for row in jsondata['rows']:
#print row['text']
a=str(row['name'])
print a
return a
search()
I am trying to call this function in an HTML file using Flask
{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>Welcome to the Rating app<h2>
<h3>This is the home page for the Rating app<h3>
</div>
<body>
<p>{{ search.a }}</p>
</body>
{% endblock %}
My routes file is as follows:
from flask import Flask,render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello gugugWorld!'
#app.route('/crawl')
def crawl():
return render_template('crawl.html')
There are many ways to do this:
1 - You can register a new Jinja2 filter
2 - You can pass your function as a Jinja2 parameter (This one is easier)
For method 2:
#app.route('/crawl')
def crawl():
return render_template('crawl.html', myfunction=search)
On the template call the parameter has a function
{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>Welcome to the Rating app<h2>
<h3>This is the home page for the Rating app<h3>
</div>
<body>
<p>{{ myfunction() }}</p>
</body>
{% endblock %}
Related
I try to pass information to an html template from a view function. Every time I try to call the variable from the html template it doesn't show anything.
Here is my configure_peplink.html:
{% extends "base_generic.html" %}
{% block content %}
<h1>Configure Peplink</h1>
<p>Configure a Peplink router from the web. This was designed by <em>Valorence LLC</em></p>
{% if peplink %}
<p>Serial Number: {{ peplink.serial_number }}</p>
<p>IP Address: {{ peplink.ip_address }}</p>
<p>Mac Address: {{ peplink.mac_address }}</p>
<p>Name: {{ peplink.name }}</p>
{% else %}
<p>No Data Found Off Device</p>
{% endif %}
{% endblock %}
Here is the view function configure_peplink:
def configure_peplink(request, peplink):
selected_peplink = PeplinkDevice.objects.get(serial_number=peplink)
print(selected_peplink.ip_address)
print(selected_peplink.serial_number)
print(selected_peplink.mac_address)
context = {
'peplink': selected_peplink
}
return render(request, 'configure_peplink.html', context=context)
Here is the url line to call the view:
re_path(r'^configurepeplink/(?P<peplink>.*)/$', views.configure_peplink, name='configurepeplink')
I've tested to make sure that the context has data in it (as seen with the print statements). Even though the context variable has data and is getting past the if statement in the html template it still doesn't display any data. I have tried clearing my cache on the browser and restarting all my services (django, celery, redis-server).
Here is a picture of the webpage:
The peplink variable (which is being used by the regex url and the view function) seems to be causing the problem. Change the name of the key or change the regex url variable for this to work. To get this to work by changing the key name in the view function do the following in the view function:
def configure_peplink(request, peplink):
selected_peplink = PeplinkDevice.objects.get(serial_number=peplink)
print(selected_peplink.ip_address)
print(selected_peplink.serial_number)
print(selected_peplink.mac_address)
context = {
'selected_peplink': selected_peplink
}
return render(request, 'configure_peplink.html', context=context)
Then change the html template to the following:
{% extends "base_generic.html" %}
{% block content %}
<h1>Configure Peplink</h1>
<p>Configure a Peplink router from the web. This was designed by <em>Valorence LLC</em></p>
{% if selected_peplink %}
<p>Serial Number: {{ selected_peplink.serial_number }}</p>
<p>IP Address: {{ selected_peplink.ip_address }}</p>
<p>Mac Address: {{ selected_peplink.mac_address }}</p>
<p>Name: {{ selected_peplink.name }}</p>
{% else %}
<p>No Data Found Off Device</p>
{% endif %}
{% endblock %}
Guys actually i am expecting the django view should return only the tag like
def load_tags():
return httpresponse("<span>span tag</span>")
def home(request):
return render(request, 'index.html',{"func":load_tags()})
html file
<h2>Calling python function {{ func }} </h2>
-In browser it displayed as
Calling python function <HttpResponse status_code=200, "text/html; charset=utf-8">
-But i am expecting as
Calling python function span tag
Guys can you help me to achieve this functionality
I tried to solve your requirement like this...
views.py
def TagsView():
html_h1 = "<h1>Hello django</h1>"
html_italic = "<h4><i>Hello django</i></h4>"
html_hr = "<hr>"
my_code = "<code>print('Hello world')</code>"
return html_h1,html_italic,html_hr,my_code
def DemoView(request):
context = {"func":TagsView()}
return render(request, 'index.html',context)
HTML Code
{% block body %}
{% autoescape off %}
{% for i in func %}
{{i}}
{% endfor %}
{% endautoescape %}
{% endblock body %}
Output
I have codes for a simple message blog that very body can leave message. One of the problems is that the message display from sqlite db is without format, e.g. without paragraph. How can I impove it (or add markdown enable)? I appreciate your help. Thank you.
main app py
#app.route('/')
def index():
conn = db_conn()
posts = conn.execute('SELECT * FROM table_posts').fetchall()
conn.close()
return render_template('index.html', posts=posts)
#app.route('/create_new_post', methods=('GET', 'POST'))
def create_new_post():
if request.method == 'POST':
content = request.form['content']
conn = db_conn()
conn.execute('INSERT INTO table_posts (content) VALUES (?)', (content,))
conn.commit()
conn.close()
return redirect(url_for('index'))
else:
return render_template('create_new_post.html')
index.html
{% extends 'base.html' %}
{% block title %}
Simple Message Board
{% endblock %}
{% block content %}
{% for post in posts %}
<br>
<div class="card">
<div class="card-body">
<p class="card-text"> {{ post['content'] }} </p>
<span class="badge badge-secondary">{{ post['time_stamp'] }}</span>
</div>
</div>
{% endfor %}
{% endblock %}
The outcome i want is as follows:
Text of 1st line
Text of 2nd line
Text of 3rd line
But the actual content displayed is as follows:
Text of 1st line Text of 2nd line Text of 3rd line
I think you are trying to render the body as html not as text.
jinja autoescapes the text , you can stop autoescaping,
For that you can use the safe filter of jinja.
{{ post['content']|safe }}
You can also see the docs
How do I pass in a variable into a template in Jinja2?
I can normally do it like
<p>Hello, {{ var }}</p>
And then in python do:
#app.route('/hello')
def hello():
return render_template('hello.html', var = "World")
Which will result in:
Hello, World
But, let's say I want a custom bg-color for every page.
If I try
<body bgcolor="{{ bg_color }}">
</body>
and in python do:
#app.route('/hello')
def hello():
return render_template('hello.html', bg_color = "black")
It doesn't work! Can anyone help?
use jinja2 template inheritance
in your base template you need to add block like
base.html
[..]
<body{% block body_attributes %}{% endblock %}>
[..]
and then in child templates you extend base.html template like:
page1.html
{% extends "base.html" %}
{% block body_attributes %}class="bg-red"{% endblock %}
[..]
page2.html
{% extends "base.html" %}
{% block body_attributes %}class="bg-blue"{% endblock %}
[..]
you can add other attributes (id, data-spy="scroll" data-target="#navbar-example3" data-offset="0" if you are using the bootstrap scrollspy ... ) for the body tag depending on the page
I don't think you can bind class like that. Here is an example of conditional class binding if its useful in your case.
<div class="{% if black_backgroud %} black {% endif %}">...</div>
and in python
#app.route('/hello')
def hello():
return render_template('hello.html', black_backgroud = True)
I am working on a small web app to view some logfiles. But the
queries I issue to the database use to get very big.
I wanted to implement some pagination following this example pagination.
I put the class into a single file which gets loaded in the Flask view. Next I implemented
my pagination view like this:
#app.route('/index/', defaults={'page':1})
#app.route('/index/page/<int:page>')
def index(page):
count = db_session.execute("select host,facility,level,msg from messages").rowcount
tblqry = db_session.execute("select host,facility,level,msg from messages").fetchmany(size=1000)
if not tblqry and page != 1:
abort(404)
pagination = Pagination(page, PER_PAGE, count)
return render_template('index.html', pagination=pagination, tblqry=tblqry)
after that I created a macro file named _pagination_helper.html with the macro contents from the macro example. Then I imported the pagination_helper macro with:
{% from "_pagination_helper.html" import render_pagination %}
but when I then try to do something like this:
{{ render_pagination(host[0]) }}
flask claims:
UndefinedError: 'str object' has no attribute 'iter_pages'
so why does flask fails to find the 'iter_pages' because I included the pagination class in the views file?
And also I am not really sure where to put the URL Generation Helper from the How To.
Edit:
This is what my pagination_helper looks like:
{% macro render_pagination(pagination) %}
<div class=pagination>
{% for page in pagination.iter_pages() %}
{% if page %}
{% if page != pagination.page %}
{{ page }}
{% else %}
<strong>{{ page }}</strong>
{% endif %}
{% else %}
<span class=ellipsis>…</span>
{% endif %}
{%- endfor %}
{% if pagination.has_next %}
Next »
{% endif %}
</div>
{% endmacro %}
You are expected to pass a Pagination object to the macro, not a string. host[0] is a string, not the pagination value you created in your view function.
Use:
{{ render_pagination(pagination) }}