I've simple 2 line code :
#app.route('/contact/')
def contact():
flash('We are reachable at ')
return render_template('contact.html')
I get the message 'We are reachable at' at /contact but it appears are normal text message. It doesn't background color(blue) or disappears after seconds.
where contact.html contains
{% extends "layout.html" %}
{% block title %}Contact{% endblock title %}
{% block body %}
<h2> Contact Us </h2>
Your email address must be valid as this is where reply
will be sent. We do not share this address with anybody.
{% endblock body %}
Please have a look at this. this might help you
<!doctype html>
<title>My Application</title>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class="flashes">
{% for message in messages %}
<div class="message_flash">{{ message }}</div>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block body %}
{% endblock %}
and Do some styling with the css
p {
color:blue;
}
And add some jquery to the code
$(function() {
// setTimeout() function will be fired after page is loaded
// it will wait for 5 sec. and then will fire
// $(".message_flash").hide() function
setTimeout(function() {
$(".message_flash").hide('blind', {}, 500)
}, 5000);
})
Hope this helps you.
I think what you need is some CSS to make it look nice. If you add some bootstrap to your base.html/layout.html, you can do this in base.html/layout.html.
{% with messages=get_flashed_messages(with_categories=true) %}
{% for category, message in messages %}
<div class='alert alert-{{category}} text-center alert-dismissible fade show m-auto'>
{{ message }}
</div>
{% endfor %}
{% endwith %}
And now whenever you are to display a flash message, do this in your route.
#app.route('/')
def index():
flash('Your message here', 'your bootstrap category[eg:success, primary, etc]')
return reder_template('contact.html')
Related
#app.route("/user")
def user():
if "user" in session:
user = session["user"]
return render_template("user.html", user=user)
else:
flash("You are not logged in")
return redirect(url_for("login")
This is the python code and below is the html
{% extends "base.html" %}
{% block title %} User {% endblock %}
{% block content %}
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for msg in messages %}
<p>{{msg}}</p>
{% endfor %}
{% endif %}
{% endwith %}
<p>Welcome, {{user}} </p>
{% endblock %}
Problem: jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'endwith' ...and i cannot figure out what is the problem. Im pretty sure its something obvious.
Debugger shows me two problems: first in python codefile and the second in the user.html file.
And here is the traceback:
enter image description here
on views.py i have used
from django.contrib import messages
def personal_detail(request):
messages.success(request, 'Form submitted successfully.')
(some lines of code here)
apply_online.save()
return render(request,'users/applyonline.html')
and on templates
<div>
{% if messages %}
{% for message in messages%}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
</div>
<div class="row">
{% block content %}{% endblock %}
</div>
its working fine but I actually want to generate unique serial number like SK(date)(year)(serial_number) of this format ,can you please help me with this?
I have a jinja2 code in my
base.html
{% block body %}]
{% block messages %}
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }} alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-
label="Close"><span aria-hidden="true">×
</span></button>
{{ message }}
</div>
{% endfor %}
{% endif %}
{% endwith %}
{%endblock messages%}
{% endblock body %}
and in the
entry.html
{% extends "base.html" %}
{% block body %}
Body text goes here
{% endblock body %}
The problem is until I don't manually call super() in the messages block from the child template jinja2 doesn't display the flash messages.
I'm a total beginner so I maybe completely wrong about how nested blocks work. Can I call the flashed messages without calling super()?? .
I'm using flask-bootstrap to use the Bootstrap front-end for a flask web application. Unfortunately, since I've started using flask-bootstrap and flask-nav, I'm not able to display flash messages.
This is the base.html:
{% extends 'bootstrap/base.html' %}
{% block navbar %}
{{ nav.mynavbar.render() }}
{% endblock %}
<html>
<body>
<hr>
<div class='container'>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
{% endwith %}
{% block content %}{% endblock %}
</div>
</body>
</html>
This is one of the view that should flash a message when a change is saved:
#app.route('/model/<model_name>/edit', methods=['GET', 'POST'])
def edit(model_name):
"""Edit model's configuration.
Args:
model_name [str]: The name of the model we want to change the
configuration.
"""
# return to index page if model is not found in the database
model = DSModel.query.filter_by(name=model_name).first()
if not model:
flash('Model {} not found.'.format(model_name))
return redirect(url_for('index'))
# pre-load current model's configuration
form = ConfigurationForm()
# if it's a POST request, it means the user is trying to change the model's
# configuration. Save changes in the database
if request.method == 'POST': # and form.validate_on_submit():
model.configuration.configuration = form.value.data
model.configuration.datetime = datetime.datetime.utcnow()
db.session.add(model)
db.session.commit()
flash('Your changes have been saved.', 'success')
return redirect(url_for('edit', model_name=model_name))
else:
form.value.data = model.configuration.configuration
return render_template('edit.html', form=form)
Finally, this is the __init__.py:
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import Navbar, View
from flask_sqlalchemy import SQLAlchemy
nav = Nav()
#nav.navigation()
def mynavbar():
return Navbar(
'Dashboard',
View('Home', 'index'),
View('Login', 'login')
)
app = Flask(__name__)
Bootstrap(app)
nav.init_app(app)
app.config.from_object('config')
db = SQLAlchemy(app)
from app import views, models
I think there must be something funky with my base.html file, but I'm not terribly familiar with HTML, so I'm not able to find what's wrong. I've looked into examples online (i.e. here), but the format seems to be pretty similar to what I'm doing.
EDIT: This is the edit.html file:
{% extends 'base.html' %}
{% block content %}
<h1>Update configuration</h1>
<form action='' method='post' name='configuration'>
<p>
Please update the current model configuration:<br>
{{ form.value(cols='150', rows='20') }}
<p><input type='submit' value='Save'></p>
</form>
{% endblock %}
Try to edit your base.html to this:
{% extends 'bootstrap/base.html' %}
{% block navbar %}
{{ nav.mynavbar.render() }}
{% endblock %}
<html>
<body>
<hr>
<div class='container'>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
</div>
{% block content %}{% endblock %}
</div>
</body>
</html>
I'm trying to incorporate an template tag/inclusion tag into my sidebar for the site. The main section of the page updates properly when I put:
{% if user.is_authenticated %}
<h1> Hello {{ user.username }}
{% else %}
<h1> Hello </h1>
{% endif %}
When I try to use the same principle in my template tag/sidebar, it seems to ignore user.is_authenticated and will always show 'login' and 'register', when it should be just showing 'logout'.
The body of the html (main index page):
{% load Kappa_extras %}
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-2" id="side_section">
{% block sidebar %}
{% get_game_list %}
{% endblock %}
</div>
<!--Main section-->
<div class="col-sm-10" id="main_section">
{% block body %}
{% endblock %}
</div>
</div>
</div>
The get_game_list function from 'Kappa_extras':
from django import template
from Kappa.models import Game, Game_Page
from django.contrib.auth.models import User
register = template.Library()
#register.inclusion_tag('Kappa/sidebar.html')
def get_game_list():
return {'game_list': Game.objects.all()}
and the 'Kappa/sidebar.html':
<div id="side_default_list">
<ul class="nav">
<li>Kappa</li>
{% if user.is_authenticated %}
<li>Log Out</li>
{% else %}
<li>Log In</li>
<li>Register</li>
{% endif %}
</div>
I checked a few older inquires though none of them are working properly. I tried putting request into def get_game_list(request): but it just said did not receive value for the argument. How do I get the sidebar to update properly when user.is_authenticated?
You need to pass the user to your inclusion tag.
#register.inclusion_tag('Kappa/sidebar.html')
def get_game_list(user):
return {'game_list': Game.objects.all(), 'user': user}
Then in your template, call the tag with
{% get_game_list user %}
Alternatively, you can set takes_context=True in your inclusion tag, so that you can access the user from the template context.
#register.inclusion_tag('Kappa/sidebar.html', takes_context=True)
def get_game_list(context):
return {'game_list': Game.objects.all(), 'user': context['user']}
In this case, you don't need to pass the user to the template tag any more.
{% get_game_list %}
See the docs for more information and other examples.