Python Forum

Full Version: Flask: Making my first web site
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3 4
I'm following Corey Schafer's tutorial and it all works well on his end but this is what happens on mine...

first, I created flaskblog file
from flask import Flask, render_template 
app = Flask(__name__)

posts = [
    {
	    'author': 'Corey Schafer',
		'title': 'Blog Post 1',
		'content': 'First post content',
		'data_posted': 'April 20, 2018'
	},
	{
	    'author': 'Jane Doe',
		'title': 'Blog Post 2',
		'content': 'Second post content',
		'date_posted': 'April 21, 2018'
	}
]

@app.route("/")
@app.route("/home")
def home():
    return render_template('home.html', posts=posts)
	
@app.route("/about")
def about():
	return render_template('about.html', title=About)
	
if __name__ == '__main__':
	app.run(debug=True)
then home page
 <!DOCTYPE html>
<html>
<head>
    {% if title %}
        <title>Flask Blog - {{ title }}</title>
	{% else %}
	    <title>Flask Blog</title>
	{% endif %}
</head>
<body>
    {% for post in posts %}
	    <h1>{{ post.title }}</h1>
		<p>By {{ post.author }} on {{post.date_posted}} </p>
		<p>{{ post.content }}</p>
    {% endfor %}
</body>
</html> 
and about page
 <!DOCTYPE html>
<html>
<head>
    {% if title %}
        <title>Flask Blog - {{ title }}</title>
	{% else %}
	    <title>Flask Blog</title>
	{% endif %}
</head>
<body>
    <h1>About Page</h1>
</body>
</html> 
when I try to open about page http://localhost:5000/about this is what I get:
Error:
NameError: name 'About' is not defined 127.0.0.1 - - [23/Jun/2019 01:52:32] "GET /about?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 - 127.0.0.1 - - [23/Jun/2019 01:52:32] "GET /about?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 - 127.0.0.1 - - [23/Jun/2019 01:52:32] "GET /about?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 - 127.0.0.1 - - [23/Jun/2019 01:52:32] "GET /about?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 - 127.0.0.1 - - [23/Jun/2019 01:52:32] "GET /about?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
I understand that 'About' is not defined but I don't understand how the code from the tutorial works. What did Corey do so differently? Huh
Here is link to code.
So you need to have same folder structure and files as in Repo.
You can use DownGit and easy way to get a single folder in Repo if you not familiar with Git.
Just copy and paste link from Repo into DownGit.

So i did test download and place content in any folder and start python flaskblog.py
E:\all_flask\2019\02-Templates
λ python flaskblog.py
 * Serving Flask app "flaskblog" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 334-187-997
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [23/Jun/2019 09:25:33] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [23/Jun/2019 09:25:34] "GET /static/main.css HTTP/1.1" 200 -
127.0.0.1 - - [23/Jun/2019 09:25:43] "GET /about HTTP/1.1" 200 -
127.0.0.1 - - [23/Jun/2019 09:25:44] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [23/Jun/2019 09:25:45] "GET / HTTP/1.1" 200 -
It work correct switch to about page and back home.

Error:
NameError: name 'About' is not defined
Also notice that about.html is not capitalize,as you have About.
Hi,

Quote:What did Corey do so differently?
Just compare the code. Your code goes ... title=About , the tutorial goes ... title='About'. I guess you see the difference now :-)

Regards, noisefloor
snippsat, I simply don't understand your message. Probably because I'm not so skilled with github.

noisefloor, you're correct. I assume that when calling other files we have to use quotes. To mention that 'about' works as well.
(Jun-23-2019, 11:10 PM)Truman Wrote: [ -> ]snippsat, I simply don't understand your message. Probably because I'm not so skilled with github.
That's why linked to DownGit,just copy this link to DownGit.
Then get zip file of all files in folder.
Hi,

Quote: I assume that when calling other files we have to use quotes.
No, actually that's plain Python syntax.

return render_template('about.html', title=About) calls the render_template method, the 1st argument is the template to render. The key word argument title binds something to the variable title to be used within the context of the template. So title=About would bind the variable About to title - but a variable About is not existing in your code. title='About' binds the string About to title - which of course works.

Regards, noisefloor
Makes sense.

snippsat, I started using downgit. It's good.

Since this topic is devoted to Schafer's tutorial I will give myself the freedom to ask more questions.
Let's take a look at layout.html page
 <!DOCTYPE html>
<html>
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    {% if title %}
        <title>Flask Blog - {{ title }}</title>
	{% else %}
	    <title>Flask Blog</title>
	{% endif %}
</head>
<body>
    <header class="site-header">
	  <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
		<div class="container">
		  <a class="navbar-brand mr-4" href="/">Flask Blog</a>
		  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
			<span class="navbar-toggler-icon"></span>
		  </button>
		  <div class="collapse navbar-collapse" id="navbarToggle">
			<div class="navbar-nav mr-auto">
			  <a class="nav-item nav-link" href="/">Home</a>
			  <a class="nav-item nav-link" href="/about">About</a>
			</div>
			<!-- Navbar Right Side -->
			<div class="navbar-nav">
			  <a class="nav-item nav-link" href="/login">Login</a>
			  <a class="nav-item nav-link" href="/register">Register</a>
			</div>
		  </div>
		</div>
	  </nav>
	</header>
    <div class="container">
	   {% block content %}{% endblock %}
	</div>
	
   <!-- Optional JavaScript -->
   <!-- jQuery first, then Popper.js, then Bootstrap JS -->
   <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
   <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html> 
What we see is that {% block content %}{% endblock %} is within <body> tags but the whole layout page is inherited and affects home and about page. How is it possible?
The home and about page inherit everything from the layout. When calling block tags from the about or home page. What is put inside the block tags in the home or about page will be put inside the block tags on the layout template.
Hi,

Flask uses the Jinja2 template engine, one of the most (if not the most) popular template engines for Python.
Jinja2 has it's own extensive documentaiton at: http://jinja.pocoo.org/docs/2.10/

Regards, noisefloor
after adding some stuff to the app...
from flask import Flask, render_template, url_for, flash, redirect
from forms import RegistrationForm, LoginForm 

app = Flask(__name__)

app.config['SECRET_KEY'] = '24b6f628700853713c55abab2a9d8309'

posts = [
    {
	    'author': 'Corey Schafer',
		'title': 'Blog Post 1',
		'content': 'First post content',
		'data_posted': 'April 20, 2018'
	},
	{
	    'author': 'Jane Doe',
		'title': 'Blog Post 2',
		'content': 'Second post content',
		'date_posted': 'April 21, 2018'
	}
]

@app.route("/")
@app.route("/home")
def home():
    return render_template('home.html', posts=posts)
	
@app.route("/about")
def about():
	return render_template('about.html', title='About')

@app.route("/register", methods=['GET', 'POST'])
def register():
	form = RegistrationForm()
	if form.validation_on_submit():
		flash(f'Account created for {form.username.data}!', 'success')
		return redirect(url_for('home'))
	return render_template('register.html', title='Register', form=form)
	
@app.route("/login")
def login():
	form = LoginForm()
	return render_template('login.html', title='Login', form=form)

if __name__ == '__main__':
	app.run(debug=True)
...receive an error
Error:
AttributeError: 'RegistrationForm' object has no attribute 'validation_on_submit'
any idea why is this happening?
Pages: 1 2 3 4