I'm working on a project in Python, and I have part of the project working (where the user submits a post). I'm trying to make it so that when the user submits their entry, they get redirected to another page, which shows all the things they've posted. When I test this, I get redirected to the new page I made, but the page is blank. Here is my code:
class Handler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def render_str(self, template, **params):
t = jinja_env.get_template(template)
return t.render(params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
class Entry(db.Model):
subject = db.StringProperty(required=True)
entry = db.TextProperty(required=True)
created = db.DateTimeProperty(auto_now_add = True)
class MainPage(Handler):
def render_front(self, subject="", entry="", error=""):
blog = db.GqlQuery("SELECT * FROM Entry ORDER BY created DESC LIMIT 10")
self.render("entry.html", subject=subject, entry=entry, error=error, blog=blog)
def get(self):
self.render_front()
def post(self):
subject = self.request.get("subject")
entry = self.request.get("entry")
if subject and entry:
e = Entry(subject = subject, entry=entry)
e.put()
self.redirect("/BlogPost")
else:
error = "To post a new entry, you must add both, a subject and your post"
self.render_front(subject, entry, error)
class BlogPost(Handler):
def get(self):
self.render("blogfront.html")
app = webapp2.WSGIApplication([('/', MainPage), ('/BlogPost', BlogPost)], debug = True)
This is just a piece of my code (I believe the error lies somewhere along those lines since my front page is working).
This is my blogfront.html:
<!DOCTYPE html>
<html>
<head>
<title>Blog </title>
</head>
<body>
{% for entry in blog %}
<div class="entry">
<div class="entry-subject">{{entry.subject}}</div>
<label>{{entry.created}}</label>
<hr>
<pre class="entry-body">{{entry.entry}}</pre>
</div>
{% endfor %}
</body>
</html>
entry.html is loading while blogfront.html is not. I'm not sure where I'm going wrong with this. I would appreciate any help. Thanks in advance.
Going by your comments to questioners the issue is that while you define blog
in the render_front()
method, it's a local variable so it vanishes when the method returns. Try retrieving the data again in your BlogPost()
method and pass that as the blog
argument to self.render()
. Without any blog data the template will indeed render as empty.
So your updated method might read:
class BlogPost(Handler):
def get(self):
blog = db.GqlQuery("SELECT * FROM Entry ORDER BY created DESC LIMIT 10")
self.render("blogfront.html", blog=blog)
assuming that you want to see the same data you display in MainPage()
, but you may well want something else.