我正在使用 flask-mongoengine 并且我的模型有Post
字段title
,slug
和. 每个都有一个唯一的,每个都需要至少有 1 个标签。至少有 1 个元素的 a也是如此。body
tags
Post
slug
Post
tags
list
strings
class Post(db.Document):
created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
title = db.StringField(max_length=255, required=True)
slug = db.StringField(max_length=255, required=True, unique=True)
body = db.StringField(required=True)
tags = db.ListField(db.StringField(max_length=255), required=True) #each post should have at least one tag
def get_absolute_url(self):
return url_for('post', kwargs={"slug": self.slug})
def __unicode__(self):
return self.title
meta = {
'allow_inheritance': False,
'indexes': ['-created_at', 'slug', 'title', 'tags'],
'ordering': ['-created_at'],
'collection': 'posts',
}
当我在模板中创建用于输入新帖子的表单时,每个标签都输入到一个带有名称的新文本框中,tags
所以如果我有 3 个标签,Post
那么将有 3 个文本框,每个都有名称tags
这是视图的方式
from flask.ext.mongoengine.wtf import model_form
class CreateEdit(MethodView):
form = model_form(Post) #Gets object of class PostForm which is a subclass of ModelForm, ModelForm is a subclass of Form
def post(self, slug = None):
form = self.form(request.form) #Populate PostForm with data from the request
post = Post()
form.populate_obj(post)
post.save()
flash('Update successful')
现在我在浏览器中遇到mongoengine.base.ValidationError
错误。我在发布请求中传递的数据(礼貌:Firebug)
title: third post
slug: 3rd
body: this is the 3rd post
tags: third
tags: last
当我在调试器中检查时request.form
显示
werkzeug.datastructures.ImmutableMultiDict({'body': u'this is the 3rd post \r\n ', 'title': u'third post', 'slug': u'3rd', 'tags': u'third'})
现在表格中有多个tags
,但字典中只有一个。这没关系,因为它是一个字典,所以不能有多个具有相同名称的键。但是当我检查form.data
它显示
{'body': u'this is the 3rd post \r\n ', 'title': u'third post', 'created_at': datetime.datetime(2012, 12, 24, 14, 7, 18, 97273), 'tags': [], 'slug': u'3rd' }
该tags
字段是一个空列表,这是荒谬的,因为它应该填充tags
from request.form
。另外,如果我进入print request.form
调试器,我会得到
ImmutableMultiDict([('body', u'this is the 3rd post \r\n '), ('title', u'third post'), ('slug', u'3rd'), ('tags', u'third'), ('tags', u'last')])
因此,这意味着request
对象保留了同名的多个值以在representation( __repr__
)中显示它,但只将一个值传递给ModelForm
对象。但我ModelForm
的没有任何价值tags
。
怎么了?