how to link an html file to another html in flask - html

my files in templates
- main.html
- page1.html
my code
def main():
return render_template('main.html')
html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
users
</body>
</html>
it doesn't work and gives me Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

You should provide the route(url) to the template in the function main() using a decorator like this:
#app.rout("your/url")
def manin()
return render_template("your_template.html")
Another thing, you should create a folder(directory) called templates, and place all your templates in it so that flask can detect them, otherwise, flask will not detect the templates, unless you tell it to look elsewhere and you do not want to bother yourself with it right now. Just put all your templates in a directory called templates that it in the same level as your app.

try this:
In main.py:
from flask import Flask, render_template
app = Flask(__name__)
app.config['SECRET_KEY'] = "YourFlaskSafetyKeyHere"
#app.route("/")
def Home():
return render_template("page1.html")
if __name__ == "__main__":
app.run(debug=True)
in page1.html:
<h1>Home Page</h1>
There you go! You just didn't satisfied the requirements of Flask

Related

Django - include another html file from different location

I have two htmls a.html and b.html. a.html is located in the template folder by default. b.html is located in appname/static/images/b.html, because it's a model calculation result in html format.
In a.html, I am trying to include b.html but it's not working, unless b.html is in the same template folder.
<body>
{% include 'appname/static/images/b.html' %}
</body>
questions:
how to include b.html?
how to include b.html dynamically if it's in different folder, e.g. images/username/b.html where username is different.
Here's a minimum viable example using the HttpResponse method:
from pathlib import Path
from django.conf import settings
from django.http import HttpResponse
def my_view(request):
my_html = settings.BASE_DIR / "appname" / "static" / "images" / "b.html"
with my_html.open() as f:
content = f.read()
return HttpResponse(content)

Httml Button in Django app to run a Python script

I am using Geonode that is actually a django app installed inside a docker container. What I want to do is, to edit an html page of my app and add an extra button that when the user presses it a python script will run.
So far, I have added the button in the html page, a function in my views.py file and a url in the urls.py but it doesnt seem to work.
html page
{% trans "Approve Layer" %}
views.py
def layer_approval(request):
# I keep it simple to make sure it works
return redirect('www.google.gr')
urls.py
from django.urls import path
urlpatterns += [
url(r'^layer_approval/', include('geonode.views.layer_approval'))
]
I am completely new to Django. Any advice?
Your method name and URL-pattern layer_approval and pass button name or id layer_approve.

My link to manifest.json in index.html works when I run react script 'yarn start', but not when I run 'python3 manage.py runserver'

When I run 'yarn start', my link to manifest.json in my index.html file works fine, but when I run 'python3 manage.py runserver' all I get in the terminal is:
Not Found: /manifest.json
"GET /manifest.json HTTP/1.1" 404 2234
This also happens to all of my static links and imports. I'm pretty new to Django and React, and programming as a whole, so I think that I'm just missing something simple, but I can't figure it out.
I've been trying to use {% load static %}, but the link doesn't work, even if I edit STATIC_URL in settings.py to point towards my manifest.json directory. I also attempted to edit view.py and urls.py, but all I get is syntax errors in the terminal. Other than that I'm clueless.
frontend/public/index.html
<html>
<head>
<title>WebProject</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<link rel="manifest" href="manifest.json"/>
</head>
<body style="background-color: #FAF0E6; font-family: Verdana; font-size: 40px;">
<div id="root"></div>
</body>
</html>
frontend/urls.py
from django.urls import path
from . import views
from django.conf.urls.static import static
urlpatterns = [
path('', views.index),
]
frontend/views.py
from django.shortcuts import render
def index(request):
return render(request, 'frontend/public/index.html')
I expected my browser to load manifest.json properly, along with any other links or imports, but I keep getting a blank page.
Im using React inside of Django, so when I tried to import my index.js the same "Not Found" terminal error popped up. Im assuming that if I solve the manifest.json problem, I'll also solve my other import and link problems.
I had the same issue and found this Can't get rid of missing manifest.json error
Well, in my case it was browser cache related and swapping to incognito mode was enough.
The same happened to me (blank page and unable to load manifest.json + react build's static files) and I solved the issues thanks to this excellent article
Solution -> assuming your react app (build etc.) are in a folder called frontend at the same level as your django project, in your settings.py file you need to make sure your STATICFILES_DIRS variable is set like below (don't forget the trailing coma as it is a tuple).
STATICFILES_DIRS = (
os.path.join(os.path.join(BASE_DIR, 'frontend'), 'build', 'static'),
)
In urls.py:
from django.urls import re_path
CHANGE:
urlpatterns = [
...
path('', TemplateView.as_view(template_name='index.html')]
TO:
urlpatterns = [
...
re_path('.*', TemplateView.as_view(template_name='index.html')]
Had the same error and worked for me.

Python Tornado won't load .Css file

I am currently new to Tornado and I am trying to render my HTML page using Tornado. The issue i am having is getting Tornado to allow the css file to be applied on my html page. When i run the html alone without a web server the css file is automatically incorporated and applied. Using Tornado, the html content is fine, but the css simply refuses to apply.
I've tried using the full path of both my files through the href and tornado, also I've tried placing them outside of the .py script running tornado but i get the same errors
Python Tornado code
import tornado.web
import tornado.ioloop
port = 8080
class basicRequestHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello world!")
class staticRequestHandler(tornado.web.RequestHandler):
def get(self):
self.render("C:/Users/user/Desktop/html/Project 1/index.html")
if __name__ == "__main__":
app = tornado.web.Application([
(r"/", basicRequestHandler),
(r"/site", staticRequestHandler)
])
app.listen(port)
print(f"Listening on {port}")
tornado.ioloop.IOLoop.current().start()
This is the link inside my html code. I've tried full and relative paths(same folder) but none seem to make a difference
<link rel="stylesheet" href="C:\Users\user\Desktop\html\Project
1\styles.css" type="text/css">
<link rel="stylesheet" href="styles.css" type="text/css">
The error that appears on my chrome console is:
(1) Not allowed to load local resource:
file:///C:/Users/user/Desktop/html/Project%201/styles.css
C:\Users\user\Desktop\html\Project 1\styles.css is a file path on your system. This will not work because browsers and servers communicate through HTTP URLS.
To load the CSS file, you'll need to use its URL.
Try <link rel="stylesheet" href="/site/styles.css">. Please read the documentation of using StaticFileHandler to learn more about its usage.

Is there a way to render an HTML page from Ruby?

I am developing an application that takes in the address of a web page and generates an HTML file with the source of that page. I have successfully generated the file. I can't figure out how to launch that file in a new tab. Here
This is running in Repl.it, a web-based code editor. Here's what I have:
def run
require 'open-uri'
puts "enter a URL and view the source"
puts "don't include the https:// at the beginning"
url = gets.chomp
fh = open("https://"+url)
html = fh.read
puts html
out_file = File.new("out.html", "w")
out_file.puts(html)
out_file.close
run
end
Then I'm running that code.
As I understand you just want to save html of site and open new file in your browser.
You can do it this way (I use Firefox).
require 'net/http'
require 'uri'
uri = URI.parse('https://bla-bla-bla.netlify.com/')
response = Net::HTTP.get_response(uri)
file_name = 'out.html'
File.write(file_name, response.body)
system("firefox #{file_name}")
Note: Keep in mind that site owners often block parsers, so you may have to use torify.
Now check the file
$ cat out.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bla-bla-bla</title>
</head>
<body>
<p>Bla-bla</p>
</body>
</html>
Everything worked out.
Hope it helps you.
If all you need is to open this file locally in your computer, I would perform a system call.
For example on my macOS the following would open the HTML page on my default browser:
system("open #{out_file.path}")
If you want to supply the rendered HTML to other users in your network then you will need a HTTP server, I suggest Sinatra to start with.