0
您好我有一個小Flask應用程序,它使用populate.obj方法將表單數據保存到對象。燒瓶 - 使用populate_obj後節省額外的領域
models.py:
class User(db.DynamicDocument):
username = db.StringField(unique=True)
email = db.StringField(unique=True)
role = db.IntField(default=ROLE_USER)
class Post(db.DynamicDocument):
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)
comments = db.ListField(db.EmbeddedDocumentField('Comment'))
author = db.ReferenceField(User)
## various subclasses of BlogPost
...
views.py:
class Detail(MethodView):
decorators = [login_required]
# Map post types to models
class_map = {
'post': BlogPost,
'video': Video,
'image': Image,
'quote': Quote,
}
def get_context(self, slug=None):
if slug:
post = Post.objects.get_or_404(slug=slug)
# Handle old posts types as well
cls = post.__class__ if post.__class__ != Post else BlogPost
form_cls = model_form(cls, exclude=('created_at', 'comments', 'author'))
if request.method == 'POST':
form = form_cls(request.form, inital=post._data)
else:
form = form_cls(obj=post)
else:
# Determine which post type we need
cls = self.class_map.get(request.args.get('type', 'post'))
post = cls()
form_cls = model_form(cls, exclude=('created_at', 'comments', 'author'))
form = form_cls(request.form)
context = {
"post": post,
"form": form,
"create": slug is None
}
return context
if form.validate():
post = context.get('post')
form.populate_obj(post)
post.save()
這工作得很好。但我想這樣做也節省了用戶對象:
...
if form.validate():
post = context.get('post')
form.populate_obj(post)
post(author=MyUserObject) # this fails!
post.save()
這失敗的錯誤:
TypeError: 'BlogPost' object is not callable
有人能解釋這是爲什麼,以及如何我要救我的用戶對象?我在意,我在這裏證明我對populate_obj
方法的無知。
任何幫助將不勝感激。
嗨@codegeek。道歉在我的代碼中有一個錯字。我正在將'User'對象作爲作者保存在'Post'對象中。所以失敗的行是'post(author = MyUserObject)'。 –
好的,我更新了答案。 – codegeek
這是我已有的代碼。我也想保存當前的用戶對象。 –