2
我試圖在每次點擊提交(這會在數據庫中添加更多「藝術」)後發送方法中的重定向,但我必須刷新以獲取新條目反而出現。我已經包含了我的main.py代碼和下面的html。我如何解決這個問題,所以我不必在每次提交後手動刷新。 (這是來自udacity網站開發課程)。重定向不工作,每次都必須刷新頁面
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>