I have a very simple app, that asks questions and moves to the next question when a question is answered correctly and send me an sms message. When it is answered incorrectly, a flashed message appears and the page reloads. I'm trying to push this on heroku but the flashed messages seem to be causing the app to crash. When the flashed messages are commented out, the app works well. When they are not, I see a 500 Internal Server Error.
Question: How can I push flashed messages when this app is deployed on heroku?
#app.route('/', methods=['GET', 'POST'])
def main():
if request.method == 'GET':
return render_template('landing.html')
elif request.form['answer'].lower() == "coffee":
message = "Step 1 completed"
server.sendmail(from_address, to_number, message)
return redirect(url_for('step_two'))
else:
message = "Sorry, that was the wrong answer. Please try again."
flash(message)
return render_template('landing.html')
The template that is rendering is extending the base and setup to show the flashed messages upon reloading.
{% extends "base.html" %}
{% block content %}
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flash style="list-style-type: none;">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
From doc
The flashing system basically makes it possible to record a message at the end of a request and access it on the next (and only the next) request
So I think you have to redirect it.
flash(message)
return redirect(url_for('main'))
Flask flash messages works with sessions.
It is just a long shot, but maybe you didn't defined the SECRET_KEY configuration, so your app is unable to set the messages to your session.
This was a templating error which could explain why I wasn't seeing any logs. Apparently class=flash isn't just for styling in this case.
I had:
<ul class=flash style="list-style-type: none;">
and it should have been:
<ul class=flashes style="list-style-type: none;">
Related
Hi i am trying to show a message but the django message is not showing. The way i want to access this is if i send a webhook to a function in python for example. ill send a webhook post request using postman , and i will receive the message
But if i then go to my page it is not showing
so my question is why is it working when i am using postman and not when using the browser, i also have a option to send the webhook request using a form on the app itself and ive added a refresh method as well but still nothing happpens.
is there a way to get a message on django if the python function is triggered with a webhook?
i am currently using 2 methods , both are working when using postman but neither works on the app itself
method 1
messages.add_message(request, messages.INFO, 'LONG was placed.')
{% if messages %}
{% for message in messages %}
<div class = "alert alert-{{message.tags}}">{{message}}</div>
{% endfor %}
{% endif %}
and method 2
storage = messages.get_messages(request)
for message in storage:
a=(message)
print(a)
storage.used = False
context = {'a':a}
return render(request,'crodlUSDT/syntax.html',context)
and then just calling it in my base.html {{a}}
i am new to coding in general but ive been struggling for days now so would appreciate any help, thanks
use this method for views.py:
messages.info(request, "Your message")
after in HTML files:
{% if messages %}
{% for message in messages %}
<div class = "alert alert-{{message.tags}}">{{message}}</div>
{% endfor %}
{% endif %}
I'm trying to build a form that when the login button is clicked, it displays a login succesful message. Here is the thing, I want that when the "login" button is clicked, the user gets redirected and in the redirected page (which is the home page), it should show the message. How can you do this in Django allauth with their default themes?
I've tried doing:
{% if request.user.is_authenticated %}
But the problem with this code is that the message appears each time, even when you reload the page.
The way I've done this is to use Django's login signals and messaging framework.
First, in your models.py of the app that manages users (or somewhere that gets instantiated when your Django Project is started), you can do something like this:
from django.contrib.auth.signals import user_logged_in
from django.contrib import messages
def login_tasks(sender, user, request, **kwargs):
messages.add_message(
request,
messages.INFO,
f"Welcome {user.username}, you have logged in.",
}
user_logged_in.connect(login_tasks)
Then in your template:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
More on Django's login signals: https://docs.djangoproject.com/en/3.1/ref/contrib/auth/#module-django.contrib.auth.signals
More on Django's messages framework: https://docs.djangoproject.com/en/3.1/ref/contrib/messages/
Good luck!
I created a model form.Is it possible to add some message in context in views.py ?
Actually i want to display a success message in template page when form is submitted and data added in database.
for example i want to do this:
if form.save:
msg = 'Data inserted successfully'
context = {'msg': msg,}
I want to save success message in my context so therefore i will show in my template page
For showing the message after model save, you can follow this Stack Over Flow Question - Django: customizing the message after a successful form save
Please this messages functionality given by django framework for onetime messages. This is the second answer provided for the above question. There are a lot of ways mentioned in the documentation that could be implemented.
Simplest one is -
In Views.py:
from django.contrib import messages
messages.add_message(request, messages.INFO, 'Data inserted successfully.')
In template:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
I am using django messaging framework to display a one time message. Everything is working fine except its not being rendered properly. Not able to figure out the issue.
Python code:
#receiver(user_signed_up)
def on_user_signed_up(sender, request, user, **kwargs):
context={'request':request}
msg='You have completed the first step of Getting started with MDN' % wiki_url(context, 'MDN/Getting_started')
messages.success(request, msg)
jinja2 code:
<div class="one time message">
{% if messages %}
<ul>
<li>{{ _('messages') }}</li>
</ul>
{% endif %}
</div>
Desired output: You have completed the first step of Getting started with MDN
My output: You have completed the first step of <a href"replaced url">Getting started with MDN</a>
Note: wiki_url is a utility that converts the path into url.
Adding extra_tags='safe' marks the message as safe in django messages framework. The answer that starts with "another option is to..." is the one worked for me
https://stackoverflow.com/a/10124845/4297741
I am developing an application in Django using Heroku's tools and guides for doing so, and have ran into an issue. On my local dev environment I cannot get a response from my views if it I use the post method. Currently i'm using a simple form to post a collection of ids to a view.
def webinarToHS(request):
errors = []
if request.method == 'GET':
webinars = get_upcoming_webinars()
return render_to_response('webinarToHS.html', {'webinars': webinars.json(), 'length': len(webinars.json())/2}, RequestContext(request))
elif request.method == 'POST':
method = request.method
return HttpResponse("test")
In the console it comes back with a 200 response ok. However the browser displays a blank html page (empty body tags).
On the production/heroku server, i get back a response, so I don't believe there is an issue with the code itself but rather with my settings file. I went back through the heroku django setup guide and used an environment variable on my local machine to switch those settings off if i'm in local dev but I am still having this issue.
Can anyone give me a clue as to where to start looking for a fix? I'm running windows 7 with a virtualenv wrapper, python 2.7.5 and django 1.5
Thanks.
As per requested in the comments, the WebinarToHS template file is as below:
<html>
<head>
<title>Add Webinars to Hubspot</title>
<style>
html, body {background-color: #eee;}
#wrapper {background-color: #fefefe; width:60%; margin:0 auto; position:relative; margin-top:50px; padding:25px;}
form {text-align:center;}
label {font-weight:bold;}
.submit {float:right;}
.check {float:left; text-align:left; max-width:48%; margin-right:2%;}
</style>
</head>
<body>
<div id="wrapper">
<form name="form" action="{%url 'G2WApi.views.webinarToHS' %}" method="post">
{% csrf_token %}
<label for="webinarKey">Choose the Webinar(s) you would like to add to hubspot:</label><br/><br/>
<div class="check">
{% for webinar in webinars %}
<input type="checkbox" name="webinars[]" value="{{ webinar.webinarKey }}" />{{ webinar.subject }}<br/>
{% if forloop.counter|divisibleby:length %}
</div><div class="check">
{% endif %}
{% endfor %}
</div>
<div style="clear:both; height:10px;"></div>
<input class="submit" type="submit" value="Add to Hubspot" />
</form>
</div>
</body>
</html>
Although it doesn't actually solve the question at hand, I found a way that was much better for what I was trying to do. I discovered that everything in my code for the POST Method worked except the output or rendering of a template. HttpRedirection worked, and also the Django Messages System. I found a tutorial on how to use that and it works perfectly for posting responses back to the originating template.
The Django Messaging system, for those who aren't aware, is a way to add details back to the originating request object. Here's a snipper
messages.success(request, "success message")
return HttpResponseRedirect(request.path)
The first line of code is attaching the message to the request object (in this case the same one that was passed in to the view) and then in the second line of code we are just redirecting back to the requesting path. Django handles all the rest you just have to add some code to your template like follows:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
to loop through and display your messages however you wish. I hope this helps someone.