Reputation: 739
I am attempted to redirect in the post method every time i hit submit (which adds more "art" to the database) but I have to refresh afterwards to get the new entry to show up instead. I have included my main.py code and the html below. How can I fix this so I don't have to manually refresh after every submission. (this is from the udacity web development course).
import os
import webapp2
import jinja2
from google.appengine.ext import db
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
autoescape = True)
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 Art(db.Model):
title = db.StringProperty(required = True)
art = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
class MainPage(Handler):
def render_front(self, title="", art="", error=""):
arts = db.GqlQuery("select * from Art order by created desc")
self.render("front.html", title = title, art = art, error = error, arts = arts)
def get(self):
self.render_front()
def post(self):
title = self.request.get("title")
art = self.request.get("art")
if title and art:
a = Art(title=title, art=art)
a.put()
self.redirect("/")
else:
error = "we need both a title and some artwork!"
self.render_front(error=error, title=title,art=art)
app = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)
html:
<form method="post">
<label>
<div>title</div>
<input type="text" name="title" value="{{title}}">
</label>
<label>
<div>art</div>
<textarea name="art">{{art}}</textarea>
<label>
<div class="error">{{error}}</div>
<input type="submit">
</form>
<hr>
{% for art in arts %}
<div class="art">
<div class="art-title">{{art.title}}</div>
<pre class="art-body">{{art.art}}</pre>
</div>
{% endfor %}
</body>
Upvotes: 2
Views: 337
Reputation: 16563
Your redirect is working fine. The reason the new entity doesn't show up is because of eventual consistency with the GAE datastore. When you put an entity, it can take a little time before it is available to be queried.
There are workarounds, but they depend on the particular application. For example, you can store a list of keys since getting by key will always work or you could use memcache.
Upvotes: 2