Creating a validator to limit the number of table entries

33 views
Skip to first unread message

mostwanted

unread,
Dec 12, 2021, 3:29:11 AM12/12/21
to web2py-users
I am trying to create a short validator that limits the number of children that can be listed under one parent but I'm having a problem with the highlighted line because I cant use parent.id to specify the selected parent when the parent variable is referenced outside the validator function. I rightfully get:
<type 'exceptions.NameError'> global name 'parent' is not defined

Anyone on ideas on how to work around this?

def my_validator(form):
    if db((db.children.id>0) & (db.children.parent==parent.id)).count() >=10:
          form.errors.children_names=SPAN("The number of children has exceeded the required number")

def registration():
    parent=db.parent(request.args(0, cast=int)) #referenced outside the validator function
    db.children.parent.default=parent.id
    form=SQLFORM(db.children)
    if form.process(onvalidation=my_validator).accepted:
        response.flash=T('Client Registered')
    return locals()

Clemens

unread,
Dec 12, 2021, 6:45:31 AM12/12/21
to web2py-users
Hello!

Your are not referencing the parent table. I think, what you want to address, is as follows:
 if db((db.parent.id>0) & (db.children.parent==parent.id)).count() >=10:
    ...

Then the error should not occur and you are get all parents with more than 10 children.

Regards
Clemens

mostwanted

unread,
Dec 12, 2021, 8:01:37 AM12/12/21
to web2py-users
What I want is to prevent more than 10 entries of children per selected parent

mostwanted

unread,
Dec 12, 2021, 8:42:31 AM12/12/21
to web2py-users
So i decided to do this & seems to be working, I hope it fall apart, please advice if i'm wrong. I added the validator function inside the registration function & called it from the process() function, its working, i hope it wont fall apart.

def registration():
    parent=db.parent(request.args(0, cast=int))
    def my_validator(form):
        if db((db.children.id>0) & (db.children.parent==parent.id)).count() >=4:

            form.errors.children_names=SPAN("The number of children has exceeded the required number")

    db.children.parent.default=parent.id
    form=SQLFORM(db.children)
    if form.process(onvalidation=my_validator).accepted:
        response.flash=T('Client Regitered')
    return locals()

Clemens

unread,
Dec 12, 2021, 8:46:40 AM12/12/21
to web2py-users
Now parent is a valid row object, that can be referenced by parent.id. If it delivers what you want to, it's fine!

Best regards
Clemens

mostwanted

unread,
Dec 12, 2021, 9:29:38 AM12/12/21
to web2py-users
Thank you, really.
Reply all
Reply to author
Forward
0 new messages