I can use decorator to force user to login to submit a form. But I need to set it up the way that when user clicks on on submit then he should be redirected to register/signup.
Currently my form in my controller is like:
@auth.requires_login()
def survey_create():
form = SQLFORM(db.survey).process()
if form.accepted:
session.flash = 'Survey Processed'
redirect(URL('index'))
return locals()
I need to send user registration form once he clicks on submit.
Please advise.
You can change the controller as follows:
def survey_create():
if auth.is_logged_in():
def onsuccess(form):
db.survey.insert(db.survey._filter_fields(form.vars))
session.flash = 'Survey Processed'
next_url = URL('default', 'index')
else:
def onsuccess(form):
session.survey_submission = form.vars
session.flash = 'Please Register'
next_url = URL('default', 'user', 'register')
form = SQLFORM(db.survey).process(dbio=False, onsuccess=onsuccess, next=next_url)
return dict(form=form)
When calling .process
, dbio
is set to False
to prevent automatic insertion of the submission into the database. Instead, the onsuccess
callback and next_url
URL are used to control what happens upon successful form submission, depending on whether the user is logged in. If the user is not logged in, form.vars
is stored in the session, and we redirect to the registration page.
In order to insert the saved survey submission after successful registration, you can add the following code to a model file (somewhere after auth
has been defined):
def insert_survey(_):
if 'survey_submission' in session:
db.survey.insert(db.survey._filter_fields(session.survey_submission))
del session.survey_submission
session.flash = 'Survey Processed'
redirect(URL('default', 'index'))
auth.settings.register_onaccept.append(insert_survey)
The above registers a callback that will be called after registration. It checks for a survey submission saved in the session, and if found, it inserts the submission in the database and then removes it from the session.