How do I implement tags in a webapp?
I’m trying to make a basic quote sharing app using Webapp. Obviously, being able to assign arbitrary labels to each reference is crucial.
Here’s the relevant code I came up with:
(Mostly from the sample chat application from the great introductory book “Using Google App Engine”).
class Quote(db. Model):
user = db. ReferenceProperty()
text = db. StringProperty()
tags = db. StringListProperty()
created = db. DateTimeProperty(auto_now=True)
and “View”:
class QuoteHandler(webapp. RequestHandler):
def get(self):
que = db. Query(Quote).order('-created');
chat_list = que.fetch(limit=10)
doRender(
self,
'quote.htm',
{ 'quote_list': quote_list })
def post(self):
self.session = Session()
if not 'userkey' in self.session:
doRender(self, 'quote.htm', {'error' : 'Must be logged in'} )
return
msg = self.request.get('message')
if msg == '':
doRender(self,'quote.htm',{'error' : 'Blank quote ignored'} )
return
tgs = self.request.get('tags') #really not sure of this
newq = Quote(user = self.session['userkey'], text=msg, tags= tgs)
newq.put();
self.get();
In quote.htm I have:
{% extends "_base.htm" %}
{% block bodycontent %}
<h1>Quotes</h1>
<p>
<form method="post" action="/quote">
Quote:<input type="text" name="message" size="60"/><br />
Tags: <input type="text" name="tags" size="30"/>
<input type="submit" value="Send"/>
</form>
</p>
{% ifnotequal error None %}
<p>
{{ error }}
</p>
{% endifnotequal %}
<br />
<h3> The latest quotes </h3>
{% for quote in quote_list %}
<p>
{{ quote.text }}<br />
({{quote.user.account}}) <br />
{{ quote.tags }}
{{ quote.created|date:"D d M Y" }}
</p>
{% endfor %}
{% endblock %}
However, this combination is wrong. I get:
BadValueError: Property tags must be a list
Whatever I type in the tag field, and (obviously) I’m new to Python and Webapp. I googled a lot but couldn’t find any guidelines for implementing the label. So I really appreciate your help fixing this bug, or rather, I pointed out a more elegant way to handle labels.
Solution
Before creating your quote,
try using split()
to convert tgs
to a word list. Tags should be separated by spaces in your form, otherwise you can add a parameter to split
if you prefer to separate them with something else.
...
tgs = self.request.get('tags').split()
newq = Quote(user = self.session['userkey'], text=msg, tags= tgs)
...