flask-mongoengine icon indicating copy to clipboard operation
flask-mongoengine copied to clipboard

ReferenceField Problem

Open thmsaurel opened this issue 12 years ago • 1 comments

Hi everyone,

I have a connexion problem with mongoengine and wtforms.

I tried to attribute permission to User class with Role class but I can't attribute Role class foreign key to User class

This is my code :

# 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])

When saving, i've this error message :

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

I tried to remplace r.id by r and r._object_key() but no result

Thanks,

thmsaurel avatar Jun 19 '14 13:06 thmsaurel

Hi

I find the answer : SelectField doesn't return good type element for ReferenceField. So this is my new code :

# 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")

Have a nice day

thmsaurel avatar Jun 24 '14 09:06 thmsaurel