我正在使用 Udacity 指导的 Google AppEngine (Python) 开始我的第一个小项目。我曾与 Drupal 合作过。
我想在每个工作实体的页面中创建一个“编辑”链接,这将允许其作者更新实体的字段。我不太确定从哪里或如何开始实现这一目标。任何帮助将不胜感激。
这是我到目前为止所做的:
主要.py:
import webapp2
import jinja2
import os
import cgi
import urllib
from google.appengine.ext import ndb
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
autoescape = True)
def render_template(template, **params):
t = env.get_template(template)
return t.render(params)
# B A S E H A N D L E R #
#########################
class BaseHandler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.write(*a, **kw)
def render(self, template, **kw):
self.response.write(render_template(template, **kw))
# M A I N P A G E #
###################
class MainPage(BaseHandler):
def get(self):
jobs = Job.query()
self.render('index.html', jobs = jobs)
# J O B E N T I T Y #
#######################
class Job(ndb.Model):
title = ndb.StringProperty(required = True)
description = ndb.TextProperty(required = True)
requirements = ndb.TextProperty()
created = ndb.DateTimeProperty(auto_now_add = True)
class JobHandler(BaseHandler):
pass
# Created this empty class to organise its subclasses,
# because they perform 'Job' functions.
# Is this a good practice?
class NewJob(JobHandler):
def get(self):
self.render('newjob.html')
def post(self):
title = self.request.get('title')
description = self.request.get('description')
requirements = self.request.get('requirements')
if title and description:
j = Job(title = title,
description = description,
requirements = requirements)
j.put()
self.redirect('/job/%s' % str(j.key.id()))
else:
self.render('newjob.html')
class JobPage(JobHandler):
def get(self, job_id):
j = Job.get_by_id(int(job_id))
self.render('jobpage.html', j = j)
app = webapp2.WSGIApplication([
('/', MainPage),
('/newjob', NewJob),
('/job/([0-9]+)', JobPage),
], debug=True)
newpage.html:
{% extends "base.html" %}
{% block content %}
<form method="post">
<div>
<label>Job Title:<br>
<input type="text" name="title" value="{{title}}">
</label>
</div>
<div>
<label>Description:<br>
<textarea name="description" col="60">{{description}}</textarea>
</label>
</div>
<div>
<label>Requirements:<br>
<textarea name="requirements" col="60">{{requirements}}</textarea>
</label>
</div>
<input type="submit">
</form>
{% endblock %}
最后,jobpage.html
{% extends "base.html" %}
{% block content %}
{{j.title}}
{{j.description}}
{{j.requirement}}
{{j.created.strftime("%b %d, %Y")}}
{% endblock %}