使用populate_obj后保存额外的字段

时间:2013-04-01 18:42:58

标签: python flask openid wtforms flask-login

您好我有一个小型Flask应用程序,它使用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方法的无知。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:4)

所以,答案似乎是语法。这有效:

  if form.validate():
        post = context.get('post')
        form.populate_obj(post)
        post.author = g.user
        post.save()

答案 1 :(得分:-1)

这样做:

if request.POST and form.validate():
    form.populate_obj(post)
    post.save()