I'm trying to create a list of clickable links to external URLs. My HTML file looks like this
<ul>
{% for post in posts %}
<li><a href={{url_for('go_to_reddit', url=post.url)}}>{{ post.title }}</a></li>
{% endfor %}
</ul>
and the python file like this
#app.route('/redirect/"<url>"')
def go_to_reddit(url):
print("Redirecting to ", url)
return redirect(url)
I keep getting the following error whenever I press on one of the links
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
I know it's not reaching the redirect function even though it hits the URL since my console doesn't print anything.
I don't think you can have quotes in a route parameter i.e. #app.route('/redirect/"<url>"') should be #app.route('/redirect/<url>') . Put another way, try dropping the quote around <url>
If you can't have quotes in a url parameter and you need to pass a complete url, then you should consider passing it as a query parameter e.g. /redirect/?link=post.url. Then in your handler for the route, you will do url = request.values.get('link', None)
Related
I've written an app that contains an html text input:
<form method="POST" action="" enctype="multipart/form-data">
<input class="ocsp_override_box_input" type="text" id="ocsp_override" name="ocsp_override" placeholder="Override the AIA field with a URL here..." value="">
</form>
In the flask app, I access the data with the following:
ocsp_override = request.form.get('ocsp_override')
It works as expected and the rest of my code is able to use this string value and do things with it. So far, so good. The way the code works is that this field should be optional. If it is blank, then it is ignored. If data is filled in it, it runs some checks and then uses this override string later on.
The issue I'm finding is that if I complete the text form using flask dev, it works as expected, but when I reload the page and leave it blank, it appears to be caching the previous entry.
For instance, if I enter in http://example.com in the text field, the code will use that string. If I reload the page (not using F5, by reloading the get page so I can post again), and I leave the field blank, the code appears to be trying to use http://example.com again. What's weird is that if I try to print(request.form.get('ocsp_override')) then it shows nothing.
If I wait a length of time (I want to say 10 mins), and then try again, everything works as expected with the field blank.
Is there some kind of caching happening here and how can I force it to reload and be fresh every time?
You might try disabling autocomplete:
e.g.
<input class="ocsp_override_box_input" ... autocomplete="off">
And if that does not work, you can try adding a cache control header to the response to prevent the browser from caching the page:
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
return response
See this answer describing Cache-Control vs Pragma headers.
I have been 6 hours trying to figure out why doesn't the django_embed_video module work as supposed.
I followed the documentation. Created a model with VideoEmbed Field. Used it in template.html.
Added the following:
EMBED_VIDEO_BACKENDS = (
'embed_video.backends.YoutubeBackend',
)
to settings.py
All i am trying to achieve is to view a youtube video in my template, but i keep getting this error:
detect_backend(str(backend_or_url))
File "project\venv\lib\site-packages\embed_video\backends.py", line 61, in detect_backend
backend = import_string(backend_name)
File "project\venv\lib\site-packages\django\utils\module_loading.py", line 27, in import_stringraise ImportError("%s doesn't look like a module path" % dotted_path) from err
ImportError: e doesn't look like a module path
template.html
...
{% load static %}
{% load embed_video_tags %}
...
{% for tid, t in tests.items %}
<div class="embed-responsive embed-responsive-16by9"> <!-- Bootstrap responsive layout -->
{% video t.ytvideo.url %} <!-- iterate tests and get YT video of each test -->
</div>
{% endfor %}
Theory: There is an error in detecting the backend, but I can't seem to get it!
If you have a diifferent way to achieve embedding youtube video in website, it would be appreciated. I have tried embedding yt video with just snippet code copied from yt website, but i faced tons of errors on the front-end regarding the CORS policies.
I installed django CORS module and allowed origin to all websites, yet kept facing cookie issues along with other CORS policies not working, or getting yt video blocked by the browser for cookie tracking issues. Further help is appreciated. Thanks in advance.
EDIT:
Now the page loads successfully but the video doesn't appear.
Console logs: Some cookies are misusing the recommended “SameSite“ attribute
I tried the following solution but didn't work:
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'
What am i missing?
I am trying to pass my variable id to the href
{% set id = p.key().id() %}
<a href="/blog/editpost/%s" % id > Edit Post</a>
But it is showing up as /blog/editpost/%s instead of /blog/edit/93090902902 where the number is the post id.
I know how to do it using ?postId = and also
Edit Post
But with that method I have to get the last thing in the url path in my python file. I want to instead get the id request object.
What I am asking here is how can I use %s to send my variable id instead of using some other way of sending it?
I'm rendering a bunch of posts on a page where a user can browse listings and click on one of them and be sent to a 'singles page' for more information on whatever product they clicked. This method works for every link EXCEPT for the first one.
Anytime I click on the very first link of the page, I get a Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. error.
The logic I have in place for the HMTL/jinja is (everything is closed off properly, I'm cutting some unnecessary code for the sake of brevity):
{% set i = 0 %}
{% for row in data %}
{% set i = i + 1 %}
<a href="/iLike/{{ i }}">
<li>content</li>
</a>
and my python code:
#app.route('/iLike/<int:num>', methods=['GET','POST'])
def single2(num):
try:
loc = session.get('loc')
transType = session.get('transType')
data = singlesQuery()
return render_template('single.html', loc=loc,transType=transType,data=data[num-1])
except Exception as e:
return (str(e))
There is no need to build URLs manually. The best way it to use flask's built-in function url_for:
{{url_for('single2', num=i)}}
There is also no need for calculating the i manually, becaue there is built-in loop.index and loop.index0:
{% for row in data %}
<a href="{{url_for('single2', num=loop.index)}}">
I believe this should always create a valid URL.
I'm new to Django. Please help me with the below.
I have a User form who provides URL1 and URL2.. These URLs need to be passed to another Python script[redirects.py] which will do the Validation to check whether they are in a valid URL format and return the Message to the User.
Now my question is how to write my views.py so as to get this done. I got to know that we can import the redirects.py in my views.py and call it. But I'm not aware of how to print the messages in my browser. Please help. Let me know if any more info is required.
def shortcuts_process(request):
print request.POST
return HttpResponse("Source is %s\nDestination is %s" % (request.POST['source'],request.POST['destination']))
Update :
This is my script overview. I have got a python script[redirects.py] in my system which accepts Source and Destination URLs. Once accepted, it validates whether they are in URL format, then takes backup, then add them into .htaccess and display the line added to the file. While doing all this, it keeps intimating the User with the information on whats happening in the script.
Now I have made the django to create a web portal which provides the User to input source and Destination. Now i want to call the script from views.py and print all those redirects.py Script output in User's web browser.
Please help me in getting this, I have spent an entire day looking for this answer. Thanks.
Update 2:
Please let me know why the below is not getting displayed in my browser
From views.py
def shortcuts_process(request):
if 'source' in request.POST and 'destination' in request.POST and request.POST['source'] and request.POST['destination']:
src=request.POST['source']
desti= request.POST['destination']
my_result=process_input(src,desti)
return render_to_response('results.html',{'result': my_result}
From results.html :
<html>
<head>
This is the result page to User
</head>
<body>
<ul>
{% for each_line in result %}
<p>{{ each_line }}</p>
{% endfor %}
</ul>
<p>
I'm supposed to be printed</p>
</body>
</html>
From browser output :
This is the result page to User
I'm supposed to be printed
From Linux prompt :
[10/Jun/2013 04:41:11] "GET /redirects HTTP/1.1" 200 727 [10/Jun/2013
04:41:14] "GET /choice?selection=shortcuts HTTP/1.1" 200 817 The URL
is not in the right format The URL is not in the right format
[10/Jun/2013 04:41:18] "POST /shortcuts.conf HTTP/1.1" 200 125
So now my question, why the Message The URL is not in the right format is not getting displayed on browser rather it displays in Linux prompt. Please help. Thanks
Whatever string you want to display in the browser, return it in the HttpResponse.
You could try something like:
#validation.py
def validate(url1, url2):
# perform validation here
if valid:
return "urls are valid"
else:
return "urls are invalid"
#views.py
def shortcuts_process(request):
print request.POST
url1 = request.POST.get('url1', '')
url2 = request.POST.get('url2'. '')
return HttpResponse(validate(url1, url2))
Hope that helps.
For form validation, please refer to Chapter 7 in the django book (http://www.djangobook.com/en/2.0/chapter07.html)
Thanks all.. I managed to get the answer.
Rather having my function validate_url to print the values, changing it to return has given me the desired result.
I'm being so dumb to find this out. Failure is the stepping stone of Success !! :O)