我与 mongoengine 和 wtforms 存在联系问题。
我尝试将User class
的权限归属于Role 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'])
我尝试按r.id
和r
重新r._object_key()
,但没有结果
谢谢,
答案 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")
度过愉快的一天