How to render a django message after page refresh - python

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 %}

Related

Can't get twilio to show 'from' data but it will show 'to' data

I have set up a Twilio app that I want to send updates to people, but I don't want to respond to individual text. I just want them to call if there is a question. I have everything working but I want to show incoming text if one gets sent, just to make sure I don't miss a question. I am using python/flask. I have my template set up and I can get it to show me all my messages, and even who the message went to, but I can't get it to show who the message was from.
{% for msg in msgs %}
{% if msg.direction == 'inbound' %}
<p> {{ msg.from }} : {{ msg.body }} </p>
{% endif %}
{% endfor %}
This will show all my messages but won't show anything else. If I change it to {{ msg.to }} it will show who the message is to. I have also tried to request in my app.
numbs = request.form["From"]
And then iterate over it in my template using a for loop, but no such luck.
Use from_ instead of from since from is a keyword in python used for imports.

Is there any way to save success message in context in django

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 %}

Using flask flashes on heroku

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;">

Error in the following django code?

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

How do I pass template context information when using HttpResponseRedirect in Django?

I have a form that redirects to the same page after a user enters information (so that they can continue entering information). If the form submission is successful, I'm returning
HttpResponseRedirect(request.path)
which works fine. However, I'd also like to display some messages to the user in this case (e.g., "Your data has been saved" at the top of the screen). If I weren't redirecting, I'd just return these messages in the context dictionary. With the redirect, however, I can't do this.
So how can I pass template context information when using HttpResponseRedirect?
What I'm trying to do seems like it would be incredibly common, so please excuse me if I'm missing something obvious.
For the sake of completion and future reference, you can now use the messages framework. After you install it:
views.py
from django.contrib import messages
def view(request):
# your code
messages.success(request, "Your data has been saved!")
HttpResponseRedirect(request.path)
template.html
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
if you are using auth and have a logged in user you could:
http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.message_set.create
GET params are also hackable. The querystring, as mentioned in other answers, could be used.
I think the most preferred way would be to use the sessions framework. That way you can load up whatever you want in the context and get
{{ request.session.foo }}
foo could be the message or you could do:
{% ifequal request.session.foo 1 %} Nice work! {% else %} Almost! {% endifequal %}
and other fun stuff.
http://docs.djangoproject.com/en/dev/topics/http/sessions/#using-sessions-in-views
You can't. HttpResponseRedirect sends a client-side redirect (HTTP status code 302) to the browser, and then the browser re-requests another page.
You can set a URL query string on the redirect, though that will be visible to the user and anyone intercepting HTTP requests (i.e. proxies), and is therefore not suitable for sensitive information.
The best way would probably be to use a coded querystring on the redirect URL... its an old school approach.
You could do something like
/page/?m=1, /page/?m=2, etc
You would then parse that variable with request.GET in the view code and show the appropriate message.
From your views.py you hast have to put a key/value-pair into the session and then read it from the HTML template.
For example:
views.py
# your code here
request.session['vote'] = 1
return HttpResponseRedirect(request.path)
your_template.html
{% ifequal request.session.vote 1 %}
<!-- Your action here -->
{% endifequal %}
The only way I know of to pass any data with a redirect is to add GET parameters to the URL you're passing in. To avoid XSS hacks you'd want to pass a specific constant like:
[current path you're passing in]?message=saved
And then process the message=saved parameter in the handler for the path you passed in.
A somewhat more complicated way would be not passing the data in the redirect, and instead using something like http://code.google.com/p/django-notify/ to store session-based data that is displayed to the user following the redirect.
You add ?saved=1 to the query string and check for it with something like:
saved = request.GET.get('saved', False)

Categories

Resources