I am new to all these and trying to figure out how to make a simple blog post with tags. Here are the relevant parts:
Model:
class Post(db.Model):
title = db.StringProperty(required = True)
content = db.TextProperty(required = True)
when = db.DateTimeProperty(auto_now_add = True)
author = db.UserProperty(required = True)
tags = db.ListProperty(db.Category)
WTForm:
class PostForm(wtf.Form):
title = wtf.TextField('Title', validators=[validators.Required()])
content = wtf.TextAreaField('Content', validators=[validators.Required()])
tags = wtf.TextField('Tags', validators=[validators.Required()])
Template:
{% block content %}
<ul>
<h1 id="">List of Posts</h1>
{% for post in posts %}
<li>
{{ post.title } By {{ post.author.nickname() }})<br />
{{ post.content }}<br />
Author {{ post.author }} <br />
Tags {{ post.tags}} <br />
</li>
{% endfor %}
</ul>
{% endblock %}
The problem is that no matter what I enter in the tags field, the template does render an empty list (i.e. '[]') instead of the tags. I appreciate your hints to fix this.
I think you need to customize your own WTForm field instead of using TextField. There are some sample code on wtforms document.
http://wtforms.simplecodes.com/docs/0.6.1/fields.html#custom-fields
class TagListField(Field):
widget = TextInput()
def _value(self):
if self.data:
return u', '.join(self.data)
else:
return u''
def process_formdata(self, valuelist):
if valuelist:
self.data = [x.strip() for x in valuelist[0].split(',')]
else:
self.data = []
class BetterTagListField(TagListField):
def __init__(self, label='', validators=None, remove_duplicates=True, **kwargs):
super(BetterTagListField, self).__init__(label, validators, **kwargs)
self.remove_duplicates = remove_duplicates
def process_formdata(self, valuelist):
super(BetterTagListField, self).process_formdata(valuelist)
if self.remove_duplicates:
self.data = list(self._remove_duplicates(self.data))
@classmethod
def _remove_duplicates(cls, seq):
"""Remove duplicates in a case insensitive, but case preserving manner"""
d = {}
for item in seq:
if item.lower() not in d:
d[item.lower()] = True
yield item
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With