db Field unique=True

37 views
Skip to first unread message

lyn2py

unread,
Dec 6, 2016, 4:26:47 PM12/6/16
to web2py-users
Hello!

I have set a field to "unique=True", it is a generated "unique id". I write in quotes because there are no guarantees, although there is a slim chance that a generated id is repeated. In the rare case that it happens, it would raise a form.error

My question is, how do I "regenerate" the id when the form.error arises?

I tried:
form = SQLFORM(db[tablo])
if form.process().accepted:
   response
.flash = 'form accepted'
elif form.errors:
   form
.vars.gen_uid = gen_uid(4) #this is the function to generate an id
   response
.flash = 'form has errors'
else:
   response
.flash = 'please fill out the form'
return dict(form=form)


But doing the above doesn't change the value of the field "gen_uid"

I appreciate your help! :)

黄祥

unread,
Dec 6, 2016, 4:43:22 PM12/6/16
to web2py-users
had you tried uuid?
e.g.
form.vars.gen_uid = uuid.uuid4()

best regards,
stifan

Niphlod

unread,
Dec 6, 2016, 5:17:04 PM12/6/16
to web2py-users
web2py forms use postbacks (the submit is directed to the same address that generated it) so the general flow is the following:

- user hits the page
- the form was not submitted nor accepted nor errored (goes to the last else)
- user fills the forms and click submit
- form was submitted: it can be accepted or errored (goes to if form.accepted or if form.errors)

From the moment user submitted the form that errored to the form rightfully compiled there is no shared state.
If you really need what you're asking (I'm quite sure that your logic may be pleased with e.g. generate a random uid just in the "accepted" branch) you need to alter the logic: persist the need of generating a new uid somewhere, i.e. the session, and then alter the default value for uid accordingly.
Or just make your own db I/O with e.g. SQLFORM.factory .

lyn2py

unread,
Dec 7, 2016, 10:38:17 PM12/7/16
to web2py-users
Thank you Niphlod, I had to read your answer twice to fully understand what you meant. Now I get it. I appreciate your pointers!

Thank you Stifan for the suggestion. I am deliberately not using that because the result is too long, and the uid will be used on html for id and other future purposes.
Reply all
Reply to author
Forward
0 new messages