0

我有一个小型 Flask 应用程序,它使用 populate.obj 方法将表单数据保存到对象。

模型.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
...

视图.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这里证明我对这种方法的无知。

4

2 回答 2

4

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

  if form.validate():
        post = context.get('post')
        form.populate_obj(post)
        post.author = g.user
        post.save()
于 2013-04-01T21:10:55.850 回答
-1

做这个:

if request.POST and form.validate():
    form.populate_obj(post)
    post.save()
于 2013-04-01T19:30:45.140 回答