Error in the following django code? - python

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

Related

How to render a django message after page refresh

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

CS50 Finance - can't get quote from form?

I'm working my way through CS50's finance problem set. (https://cs50.harvard.edu/x/2020/tracks/web/finance/)
In this task a user should be able to submit a form on a html page to request the current price of a share in a company.
Below is what I've made so far for the quote route (using python and flask):
#app.route("/quote", methods=["GET", "POST"])
#login_required
def quote():
"""Get stock quote."""
if request.method == "POST":
quote = lookup(request.form.get("requested_share"))
if quote == None:
return apology("No share found for this symbol")
return render_template("quoted.html", quote=quote)
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("quote.html")
And here is what I've written for the "quote" html page:
{% extends "layout.html" %}
{% block title %}
Quote
{% endblock %}
{% block main %}
<form action="/quote" method="post">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="requested_share" placeholder="e.g. TSLA" type="text" />
</div>
<button class="btn btn-primary" type="submit">Request Quote</button>
</form>
{% endblock %}
Finally, here is what I've got for the "quoted" html page (where the user should be taken if their request for a quote is successful):
{% extends "layout.html" %}
{% block title %}
Quoted
{% endblock %}
{% block main %}
<p>A share of {{ quote["name"] }} costs {{ quote["price"] }}</p>
{% endblock %}
However, when I try it out, it seems to be acting as though the user hasn't typed anything in. Instead of going to the quoted.html page, it goes to the apology page from this part of the code:
if quote == None:
return apology("No share found for this symbol")
Can anyone help with this? I've been staring at it for ages, still can't see where it's going wrong. I thought it might have been something to do with the API Key, though I've followed the instructions on the page
I assumed it might have to do with the GET calls returning a None at the end
DEBUG:urllib3.connectionpool:https://cloud-sse.iexapis.com:443 "GET /stable/stock/AAPL/quote?token=[your_api_key] HTTP/1.1" 200 None
So, I've tried plugging in your code into mine and swapping out things to make sure I could recreate what you are experiencing:
if not quote:
// instead of
if quote == None:
It happened once or twice but it turned out to be wrongly entered symbols e.g. 'APPL' instead of 'AAPL' for apple stock.
I had this issue initially when nothing was being returned from the api calls through the lookup() method. If you don't see a message in your console when you lookup a stock symbol like this:
"GET /stable/stock/AAPL/quote?token=[your_api_key] HTTP/1.1" 200 None
or
"GET /stable/stock/AAPL/quote?token=[your_api_key] HTTP/1.1" 404 None
When GET returns 404 then the quote == None triggers and you get the call to the apology() function.
So if you don't see anything similar to thos lines, then that means no calls are being sent to the IEX api. I'm not sure if it's some sorta security feature (or even if that's the case, like someone else commented ensure that your api key is working properly just to be sure) but I tried making the call using the postman app by manually inserting the stock symbol and api key and after that it started working. Postman is an app for building and testing apis, you can get it here - link to Postman
This is what the result looks like in Postman:
So try that if you haven't and then checking if your console in the CS50 ide is showing the calls being made.

Add StreamingHttpResponse into middle of Django template

Python 3.6.3, Django 2.0.3
I'm new to django, but I'm trying to make a pretty simple site where someone can trigger a few tasks that were previously just misc, stand-alone python scripts. Unfortunately those tasks can take a pretty long time. I want to be able to display the output from those tasks in the middle of the following template (where {{ stream }} is) so the user has some meaningful feedback.
{% load pagePieces %}
{% page_header %}
<div class="container">
<div class="row">
<a class="btn" href="/"><i class="fa fa-chevron-left"></i> Home</a>
</div>
<div class="row row-header"><h1>{{ operation }}</h1></div>
<div class="row row-content">
{{ stream }}
</div>
</div>
{% page_footer %}
In my view file I've tried a few different things, but here's about where I'm at now (this is somewhat simplified. I took out some error handling and changed some names):
def myaction(request):
output_template = loader.get_template('myapp/process_output.html')
return StreamingHttpResponse(
output_template.render({
'operation': 'That long running task',
"stream": streaming_wrapper()
})
)
def streaming_wrapper():
output_template = loader.get_template('myapp/process_output.html')
x = yield from a_module.long_running_task()
yield output_template.render({
'operation': 'That long running task',
"stream": x
})
This does stream the output from long_running_task(), but doesn't load the rest of the template until after it's done. At other points, I've gotten the output to stream after the template, but never in the middle, which looks bad because my template has a header and a footer.
I'm not sure how to make this work, and I'm not sure if the answer is in my views or perhaps doing something more complicated with my template.
(I'm also aware this is similar to these 2 questions, but neither of them have satisfactory answers and are years old.
Django: return a StreamingHttpResponse on an existing html page
Django StreamingHttpResponse into a Template)
Try to implement the steps as per this blog of Miguel Grinberg - https://blog.miguelgrinberg.com/post/video-streaming-with-flask/page/8 (This is for for Flask). But you have to follow the same steps and also need to modify the template as per the need. These steps worked for me.

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.

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

Categories

Resources