如何通过数据存储支持这些复选框?

How to back these checkboxes by the datastore?

我想将复选框值保存到数据库中并在 google appengine 项目中使用它们。我之前的问题是关于将其存储到会话中。我修改了这个简单的 google 项目。但无法完成这项工作。它保存留言簿条目但不保存复选框。

这里是 html:

      <html>
  <body>
    {% for greeting in greetings %}
      {% if greeting.author %}
        <b>{{ greeting.author }}</b> wrote:
      {% else %}
        An anonymous person wrote:
      {% endif %}
      <blockquote>{{ greeting.content|escape }}</blockquote>
    {% endfor %}

    <form action="/sign" method="post">
<input type="checkbox" id="opt1" name="option 1" {% if not greetings.opts or "option 1" in greetings.opts %}checked="1"{% endif %} /><span class="font90" style="cursor:default;" >{{("Option 1")}} </span>
<input type="checkbox" id="opt2" name="option 2" {% if not greetings.opts or "option 2" in greetings.opts %}checked="1"{% endif %} /><span class="font90" style="cursor:default;" >{{("Option 2")}}</span>



      <div><textarea name="content" rows="3" cols="60"></textarea></div>
      <div><input type="submit" value="Sign Guestbook"></div>
    </form>

    <a href="{{ url }}">{{ url_linktext }}</a>
    <br>
    <br>



  <br>

  </body>
</html>

和helloword.py:

import urllib
import webapp2

from google.appengine.ext import db
from google.appengine.api import users

import jinja2
import os

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))


class Greeting(db.Model):
  """Models an individual Guestbook entry with an author, content, and date."""
  opts=db.StringListProperty()
  author = db.StringProperty()
  content = db.StringProperty(multiline=True, indexed=False)
  date = db.DateTimeProperty(auto_now_add=True)



def _GuestbookKey(guestbook_name=None):
  """Constructs a Datastore key for a Guestbook entity with guestbook_name."""
  return db.Key.from_path('Guestbook', guestbook_name or 'default_guestbook')


class MainPage(webapp2.RequestHandler):

  def get(self):  # pylint:disable-msg=invalid-name
    """Handle GET requests."""
    guestbook_name = self.request.get('guestbook_name')
    greetings_query = Greeting.all().ancestor(
        _GuestbookKey(guestbook_name)).order('-date')
    greetings = greetings_query.fetch(10)

    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'
##    opt=self.request.get('opts',[])



    template_values = {
        'greetings': greetings,
        'url': url,
        'url_linktext': url_linktext,

    }
##    'opts': dict.fromkeys(opt, 'checked')

    template = jinja_environment.get_template('index.html')
    self.response.out.write(template.render(template_values))


class Guestbook(webapp2.RequestHandler):

  def post(self):  # pylint:disable-msg=invalid-name
    """Handle POST requests."""
    # We set the same parent key on the 'Greeting' to ensure each greeting is in
    # the same entity group. Queries across the single entity group will be
    # consistent. However, the write rate to a single entity group should
    # be limited to ~1/second.

    guestbook_name = self.request.get('guestbook_name')
    greeting = Greeting(parent=_GuestbookKey(guestbook_name))

    if users.get_current_user():
      greeting.author = users.get_current_user().nickname()
    allopts=['option 1','option 2','option 3']
    greeting.opts=[op for op in allopts if self.request.get(op)]

##    greeting.opts=self.request.get("opts", allow_multiple=True)



    greeting.content = self.request.get('content')
    greeting.put()
    self.redirect('/?' + urllib.urlencode({'guestbook_name': guestbook_name}))


APP = webapp2.WSGIApplication([
    ('/', MainPage),
    ('/sign', Guestbook),
], debug=True)

尽管存在所有剩余缺陷,但这段代码在编辑后确实保存了一个选中复选框的列表——它从不显示它们,因为在模板中它检查greetings.opts ,它不存在,而不是检查 greeting.opts. 之前没有 s 循环中 greeting,单数, 已定义。

例如,将模板的核心更改为

    {% for greeting in greetings %}
      {% if greeting.author %}
        <b>{{ greeting.author }}</b> wrote:
      {% else %}
        An anonymous person wrote:
      {% endif %}
      <blockquote>{{ greeting.content|escape }}</blockquote>
<input type="checkbox" name="option 1" {% if not greeting.opts or "option 1" in greeting.opts %}checked="1"{% endif %} /><span class="font90" style="cursor:default;" >{{("Option 1")}} </span>
<input type="checkbox" name="option 2" {% if not greeting.opts or "option 2" in greeting.opts %}checked="1"{% endif %} /><span class="font90" style="cursor:default;" >{{("Option 2")}}</span>
      <p><p>
    {% endfor %}

    <p><p>
    <form action="/sign" method="post">

将在每个问候语之后立即显示两个复选框,具体取决于提交该问候语时的状态。

还有很多小问题(例如严格来说 HTML 使用 checked=1 是错误的,但浏览器通常会忽略这些错误),其中最糟糕的是使用古老的 db 而不是漂亮的新 ndb.

但是,模板中的这一更改(加上我之前在评论中提到的所有错误以及您的编辑现已修复)似乎确实回答了目前的问题。