flask - ReferenceField和 Wtforms

  显示原文与译文双语对照的内容
0 0

我与 mongoengine wtforms有联系。

我试图使用 Role classUser class 属性进行属性的属性化,但是不能将 Role class 属性属性属性属性属性设置为 User class

这是我的代码:


# On class File
from mongoengine import Document, StringField, ReferenceField

class User(Document):
username = StringField(unique=True)
password = StringField()
role = RefrenceField(Role, default=Role.objects.get(num=3))

class Role(Document):
num = IntField()
name = StringField()

# On form File 
from wtforms import Form, StringField, SelectField

class UserEditForm(Form):
username = StringField(u'Username', [validators.required()]
role = SelectField(u'Role', [validators.required()], choices = [(r.id, r.name) for r in Role.objects])

保存时,我有以下错误消息:


ValidationError: ValidationError (User:53a14fb0cdc4674abf452f2d) (A ReferenceField only accepts DBRef or documents: ['role'])

我试图通过 rr._object_key() 来 remplace r.id,但没有结果

谢谢,

时间: 原作者:

0 0

我发现答案:SelectField 没有返回 ReferenceField的好类型元素。

这是我的新代码:


# form File
class UserEditForm(Form):
 username = StringField(u'Username', [validators.required()])
 role = SelectField(u'Role', [validators.required()], choices=[(r.num, r.name) for r in Role.objects], coerce=int)

# Controller class
class EditUser(MethodView):
 def get_context(self, id):
 usr = User.objects.get(id=id)
 form = UserEditForm(request.form, usr)
 return {"usr": usr,"form": form}
 def post(self, id):
 context = self.get_context(id)
 form = context.get("form")
 if form.validate():
 usr = context.get("usr")
 form.populate_obj(usr)
 usr.role = Role.objects.get(num=form.role.data)
 usr.save()
 return redirect("/user_edit/" + id)
 return response("form error validation")

过 美好 的 一天 吧

原作者:
...