Variables set by docassemble
There are some special variables that docassemble sets in every interview’s variable store.
internal
_internal is a Python dictionary that is used by docassemble
but that is not intended to be used in interviews.
nav
nav is an object that is used to keep track of sections in your
interview. This is relevant if you are using the navigation bar
feature. For information about how to use it, see the documentation
for the nav functions.
session_local
session_local is a type of DAObject that can be used to store
information that is specific to the current browser session. The
“current browser session” is distinct from the “session.”
In docassemble, a “session” is a particular instance of a person
going through an interview. The interview is identified by an
interview filename, like
docassemble.example_inc:data/questions/survey.yml, and the set of
interview answers for the session in that interview is identified by a
session id like bBWTFcny09FugpRhdvfxZJKu3iPMeVtf.
The “browser session” is a different concept; it refers to a “session within a session.” If the user starts up their web browser, and enters a docassemble session, that is one “browser session.” If the user closes their web browser, then re-enters the same docassemble session, that is another “browser session.” Or, if the user uses a different device, or a different web browser application, and enters the docassemble session with it, that constitutes a separate “browser session.”
The special variable session_local is a type of DAObject, and you
can treat it as a DAObject, but its attributes will always be
dependent on the “browser session.” If the user switches to a
different browser session, the attributes of session_local that were
defined during the first browser session will not be present during
the second browser session.
mandatory: True
code: |
multi_user = True
---
mandatory: True
code: |
session_local.how_doing
final_screen
---
question: |
How are you doing today?
field: session_local.how_doing
choices:
- Well: well
- Poorly: poor
---
question: |
What is your favorite fruit?
fields:
- Favorite fruit: favorite_fruit
---
event: final_screen
question: |
Your favorite fruit is ${ favorite_fruit }
subquestion: |
% if session_local.how_doing == 'well':
I am glad you are doing well.
% else:
I am sorry you are poorly today.
% endif
Try re-joining this interview by
using a different web browser, an
incognito tab, or by closing your
browser application and opening it
again, and visiting this URL:
[${ interview_url() }](${ interview_url() })The session_local variable works using a browser cookie that is
deleted (“expires”) when the user closes the web browser application
or logs out of docassemble.
device_local
The device_local variable is similar to session_local, except that
it is tied not to a browser session, but to a device (a web browser).
If the user closes the browser application and then opens the same
browser application and enters the session again, the device_local
object will be the same as before. However, if the user connects with
a different browser application, or switches from using a laptop to
using a smartphone, the device_local object will be different.
Also, if the user opens an incognito tab, this will also appear as
different device.
mandatory: True
code: |
multi_user = True
---
mandatory: True
code: |
device_local.how_doing
final_screen
---
question: |
How are you doing today?
field: device_local.how_doing
choices:
- Well: well
- Poorly: poor
---
question: |
What is your favorite fruit?
fields:
- Favorite fruit: favorite_fruit
---
event: final_screen
question: |
Your favorite fruit is ${ favorite_fruit }
subquestion: |
% if device_local.how_doing == 'well':
I am glad you are doing well.
% else:
I am sorry you are poorly today.
% endif
Try re-joining this interview by
using a different web browser, an
incognito tab, or by closing your
browser application and opening it
again, and visiting this URL:
[${ interview_url() }](${ interview_url() })The device_local variable works using a browser cookie that is not
deleted when the when the user closes the web browser application
or logs out of docassemble.
user_local
The user_local variable is similar to session_local and
device_local, except that the variable is tied to a specific user.
It works when the user is not logged in, but when the user is
not logged in, it functions much like session_local because the
identity of an anonymous user only lasts as long as a session.
The user_local object can be useful in situations where you have a
multi-user interview with logged-in users. For example:
metadata:
require login: True
---
mandatory: True
code: |
multi_user = True
---
objects:
- client: Individual
- adverse_party: Individual
- user_local.person: Individual
---
code: |
if not hasattr(client.name, 'first'):
user_local.person = client
elif hasattr(adverse_party, 'email') and user_info().email.lower() == adverse_party.email.lower():
user_local.person = adverse_party
---
question: |
What is your name?
fields:
- First name: user_local.person.name.first
- Last name: user_local.person.name.last
---
code: |
if user_info().first_name:
user_local.person.name.first = user_info().first_name
---
code: |
if user_info().last_name:
user_local.person.name.last = user_info().last_name
---
mandatory: True
code: |
user_local.person
client.name.first
final_screenAny time you want to refer to the user, you can refer to
user_local.person. This may be an alias for client or
adverse_party, or it may have the intrisic name of
user_local.person.
url_args
url_args is a Python dictionary that is used to access parameters
passed via URL.
Users start an interview by going to a URL. A basic URL would look like this:
http://example.com/interview?i=docassemble.example_inc:data/questions/survey.ymlHere, the only parameter is i, the interview file name.
It is possible to use the URL to pass special parameters to the interview code. For example, if the user started the interview by clicking on the following link:
http://example.com/interview?i=docassemble.example_inc:data/questions/survey.yml&from=webthen the interview would load as usual, and the interview code could
access the value of the from parameter by looking in the url_args
variable in the variable store. For example, the interview could
contain the following code:
---
code: |
if 'from' in url_args:
origin_of_interviewee = url_args['from']
else:
origin_of_interviewee = 'unknown'
---
mandatory: True
question: You came from the ${ origin_of_interviewee }.
---Alternatively, you could use Python’s get method to do the same thing in less space:
---
mandatory: True
question: You came from the ${ url_args.get('from', 'unknown') }.
---You can test this out by trying the following links:
- https://demo.docassemble.org/interview?i=docassemble.demo:data/questions/testurlarg.yml&from=web
- https://demo.docassemble.org/interview?i=docassemble.demo:data/questions/testurlarg.yml&from=moon
As soon as the interview loads, the parameters will no longer appear
in the browser’s location bar. Nevertheless, the parameters remain
available in the url_args dictionary for the life of the interview.
Moreover, you can set new url_args at any time during the course of
the interview. For example:
---
mandatory: True
question: You came from the ${ url_args.get('from', 'unknown') }.
subquestion: |
% if url_args.get('fruit', 'apple') == 'apple':
I think your favorite fruit is an apple, but [click here](?fruit=orange)
if you disagree.
% else:
I see that your favorite fruit is not an apple.
% endif
---You can test this out by trying the following link: https://demo.docassemble.org/interview?i=docassemble.demo:data/questions/testurlarg2.yml&from=wild blue yonder.
The following URL parameters
have special meaning in docassemble. All others are available for
you to use and to retrieve with url_args.
i: indicates the interview file to usesession: indicates the key of the stored dictionary to useaction: used by theurl_action()functionfilename: used for retrieving documentsquestion: used for retrieving documentsformat: used for retrieving documentscache: used to clear the interview evaluation cachereset: used to restart an interview sessionnew_session: used to start a new interview sessionindex: used for retrieving documentsfrom_list: indicates that interview was launched from the Interview List page, or in a context where the user does not need to be warned when switching into a different interviewjs_target: indicates that JavaScript should be returned that places the interview into the element on the screen with anidmatching the given value.utm_source,utm_medium,utm_campaign,utm_term, andutm_content: if you have enabled ananalytics idin yourgoogleconfiguration, these UTM parameters, which are used by Google Analytics and other analytics sites, will not be processed asurl_args. Instead, they will be retained in the location bar so that they can be accessed by the JavaScript of Google Analytics or other tracking code.
role_needed
If you use the multi-user interview feature and the user reaches a
point in the interview where input is needed from a different user
before proceeding, docassemble will look for a question that
offers to sets role_event, and ask that question. docassemble
will set the variable role_needed to a list of roles capable of
answering the next question in the interview.
Variables used when finding blocks to set variables
The following variables are set by docassemble in the course of searching for blocks that will define variables.
xijklmn
You should never set these variables yourself; they will be set for you before your blocks are used.
Variables that interviews can set
role
If you use the multi-user interview feature, your interview will
need to have a default role initial block containing code that
sets the variable role to the user’s role.
speak_text
If this special variable is set to True, docassemble will
present the user with an HTML5 audio control at the top of the page.
When the user clicks it, docassemble will access the VoiceRSS
web service to convert the text of the question to an audio file and
then play that audio back for the user. This requires enabling the
voicerss setting in the configuration.
Since the VoiceRSS service costs money above the free usage tier, docassemble does not send the request to VoiceRSS until the user presses “Play” on the audio control. It also caches the results and reuses them whenever possible.
track_location
If set to True, the web app will attempt to obtain the user’s
position, based on GPS or any other geolocation feature enabled in the
browser. The location_known(), location_returned(), and
user_lat_lon() functions can be used to retrieve the information.
The most common way to use this feature is as follows:
---
include:
- basic-questions.yml
---
initial: True
code: |
track_location = user.location.status()
---This will cause track_location to be true initially, but once an
attempt has been made to gather the location, it will be set to false.
The user’s location can subsequently be obtained by accessing the
user.location object.
multi_user
If you want to use the multi-user interview feature, you need to set
multi_user to True. This is usually done in a “mandatory” or
“initial” code block.
When multi_user is set to True, docassemble will not encrypt
the interview answers (the interview session dictionary). This is
necessary so that different people can access the same interview
session. When the interview answers are encrypted (which is the
default), only the user who started the interview session can access
the interview session dictionary.
Setting multi_user to True will reduce security somewhat, but it
is necessary for allowing the multi-user interview feature and for
allowing third parties to access the interview answers via the API.
The multi_user variable can be changed dynamically over the course
of an interview. For example, at a certain point in the interview,
you could ask the user:
question: |
Would you like an attorney to review your answers?
yesno: multi_userAfter multi_user is set to True, then the next time the interview
answers are saved, encryption will not be used. Later in the
interview, you can turn encryption back on again by setting
multi_user to False.
menu_items
Interviews can add entries to the menu within the web app.
When menu_items is set to a Python list, docassemble will add
entries to the menu based on the items in the list.
Each item in the list is expected to be a Python dictionary with
keys label and url. Typically, these entries are generated using
the action_menu_item() function, which creates a menu item that
runs an “action.” (See the url_action() and process_action()
sections of the functions page for more information about what
“actions” are in docassemble, and for documentation for the
action_menu_item() function.)
---
mandatory: True
code: |
menu_items = [ action_menu_item('Review Answers', 'review_answers') ]
---Alternatively, you can set items manually:
---
mandatory: True
code: |
menu_items = [ {'url': 'https://google.com', 'label': 'Go to Google!'} ]
---Since menu items are controlled with code blocks, you can turn them
on and off during the course of the interview as necessary.
allow_cron
This variable should be set to True if you want to allow the server
to run scheduled tasks from your interview.
Variables that stand in for events
docassemble interviews ask questions or run code when required by interview logic and also when caused to do so by events and actions. These events and actions are identified using variables, which may not ever be defined by an interview.
There are some built-in variable names with special meaning:
incoming_emailis used to indicate acodeblock that should be run when an e-mail is received.role_eventis used to present a special screen when the roles system requires a change in the interview role.cron_hourlyis used by the scheduled tasks system. This event is triggered in the background, every hour, by the server. (This requires thatallow_cronbe set toTrue.)cron_dailyis similar, except runs on a daily basis.cron_weeklyis similar, except runs on a weekly basis.cron_monthlyis similar, except runs on a monthly basis.
Variables in the JavaScript context
In the web browser, there are a number of variables, most of which
begin with da, that are special and should not be overwritten. Check
the JavaScript console before using a global variable.
Some JavaScript variables you might want to access include:
daUserId- the user’s integer ID if the user is logged in, andnullotherwise.daYamlFilename- the filename of the current interview.daUsingGA- whether Google Analytics is being used.daUsingSegment- whether Segment is being used.
Reserved names
The following variables are set internally by docassemble. If you try to use these reserved names for your own purposes, you will experience errors or unexpected results.
_internal: used internally by docassemble for various purposes, including keeping track of the progress bar, storing the answers to multiple-choice questions, and tracking which questions have already been answered.allow_cron: a special variable that is set toTrueif you want to allow the server to run scheduled tasks from the interview.cron_daily: a special variable that is used as part of the scheduled tasks system.cron_hourly: a special variable that is used as part of the scheduled tasks system.cron_monthly: a special variable that is used as part of the scheduled tasks system.cron_weekly: a special variable that is used as part of the scheduled tasks system.caller: within Mako the variablecallerhas a special meaning.device_local: an object that will always be specific to a particular device of a particular user.loop: within a Mako “for” loop, this variable has special meaning.i,j,k,l,m,n: used as iterators when dictionaries or lists are used.incoming_email: a special variable that is used as part of the background processes system.menu_items: used to add items to the menu.multi_user: a special variable that is used as part of the roles system.nav: used to keep track of sections in the interview.role: used to store the role of the current user for purposes of the roles system.role_event: a special variable that is used as part of the roles system.role_needed: a special variable that is used as part of the roles system.row_index: used with tables.row_item: used with tables.self: has a special meaning in Python.session_local: an object that is specific to a particular browser session of a user.speak_text: used to indicate whether the web app should offer audio versions of each question, generated by text-to-speech synthesis.STOP_RENDERING: used in Mako templates to end a template early.track_location: used to indicate whether the web app should attempt to determine the user’s latitude and longitude.url_args: a dictionary available to interview code that contains values encoded in the URL with which the interview was initially loaded.user_local: an object that is specific to a particular user in an interview.user_dict: if you use this as a name in an interview, your interview will not behave properly.allow_cron: a special variable that is used as part of the scheduled tasks system.x: used as a reference to the underlying object when generic objects are defined.
The following names are imported automatically:
AddressAssetChildListCityDADABreadCrumbsDACloudStorageDAContextDADictDAEmailDAEmailRecipientDAEmailRecipientListDAEmptyDAFileDAFileCollectionDAFileListDAGlobalDAGoogleAPIDALinkDAListDAOAuthDAObjectDAOrderedDictDARedisDASetDAStaticFileDAStoreDATemplateDAValidationErrorDAWebDAWebErrorEventExpenseFinancialListIncomeIndividualIndividualNameLatitudeLongitudeMachineLearningEntryNameOfficeListOrganizationPeriodicFinancialListPeriodicValuePersonRandomForestMachineLearnerRelationshipTreeRoleChangeTrackerSVMMachineLearnerSimpleTextMachineLearnerThingValueaction_argumentaction_argumentsaction_button_htmlaction_menu_itemadd_separatorsall_variablesalphaas_datetimeassemble_docxbackground_actionbackground_error_actionbackground_responsebackground_response_actionboldcapitalizechainchat_partners_availableclear_explanationscomma_and_listcomma_listcommandcountries_listcountry_namecreate_sessioncreate_usercurrencycurrency_symbolcurrent_datetimedate_differencedate_intervalday_ofdecode_namedefinedefineddelete_recorddevicedispatchdocx_concatenatedow_ofencode_nameexplainfix_punctuationforce_askforce_gatherforget_result_offormat_dateformat_datetimeformat_timefrom_b64_jsonget_chat_logget_configget_countryget_default_timezoneget_dialectget_emailsget_infoget_languageget_localeget_progressget_question_dataget_session_variablesget_sms_sessionget_statusget_user_infoget_user_listget_user_secretgo_back_in_sessioninclude_docx_templateindefinite_articleindentinitiate_sms_sessioninterfaceinterview_emailinterview_listinterview_menuinterview_urlinterview_url_actioninterview_url_action_as_qrinterview_url_as_qritalicitem_labeljsonjson_responselanguage_from_browserlanguage_namelast_access_dayslast_access_deltalast_access_hourslast_access_minuteslast_access_timelocation_knownlocation_returnedloglogic_explanationmanage_privilegesmap_ofmark_task_as_performedmessagemonth_ofname_suffixneednice_numbernoun_pluralnoun_singularnoyesobjects_from_fileocr_fileocr_file_in_backgroundordinalordinal_numberoverlay_pdfpath_and_mimetypepdf_concatenateperiod_listphone_number_in_e164phone_number_is_validphone_number_partplainprevent_going_backprocess_actionqr_codequantity_nounquote_paragraphsrawrere_run_logicread_qrread_recordsreconsiderredactreferring_urlresponseretrieve_stashed_datareturning_userromanrun_action_in_sessionrun_python_moduleselectionssend_emailsend_faxsend_smsserver_capabilitiessession_tagsset_countryset_infoset_languageset_live_help_statusset_localeset_partsset_progressset_save_statusset_session_variablesset_statusset_task_counterset_titleset_user_infoset_variablesshowifshowifdefsingle_paragraphsingle_to_double_newlinesspace_to_underscoresplitstart_timestash_datastate_namestates_liststatic_imagestore_variables_snapshotsubdivision_typetask_not_yet_performedtask_performedterminate_sms_sessiontimes_task_performedtimezone_listtitle_casetodayundefineupdate_termsurl_actionurl_askurl_ofususer_has_privilegeuser_infouser_lat_lonuser_logged_inuser_privilegesvalidation_errorvaluevariables_as_jsonverb_pastverb_presentverbatimwordwrite_recordyear_ofyesnozip_file
If you include a modules block including
docassemble.base.legal, the above names will be used, as well as
the following additional names:
If you include the basic-questions.yml file from docassemble.base,
the names included by docassemble.base.legal will be included, and
the following names will also be used:
advocateblank_signaturecaseclientcourtempty_signaturejurisdictionpleadingrolerole_eventrole_neededspouseuseruser_understands_how_to_use_signature_featureuser_understands_no_attorney_client_relationship
In addition, Python uses the following names as part of the language. If you use any of these as your own variable names, you may encounter an error or an unexpected problem.
ArithmeticErrorAssertionErrorAttributeErrorBaseExceptionBufferErrorBytesWarningDeprecationWarningEOFErrorEllipsisEnvironmentErrorExceptionFalseFloatingPointErrorFutureWarningGeneratorExitIOErrorImportErrorImportWarningIndentationErrorIndexErrorKeyErrorKeyboardInterruptLookupErrorMemoryErrorNameErrorNoneNotImplementedErrorNotImplementedOSErrorOverflowErrorPendingDeprecationWarningReferenceErrorRuntimeErrorRuntimeWarningStandardErrorStopIterationSyntaxErrorSyntaxWarningSystemErrorSystemExitTabErrorTrueTypeErrorUnboundLocalErrorUnicodeDecodeErrorUnicodeEncodeErrorUnicodeErrorUnicodeTranslateErrorUnicodeWarningUserWarningValueErrorWarningWindowsErrorZeroDivisionError__debug____doc____import____name____package___absallandanyapplyasassertbasestringbinboolbreakbufferbytearraybytescallablechrclassclassmethodcmpcoercecompilecomplexcontinuecopyrightcreditsdefdeldelattrdictdirdivmodelifelseenumerateevalexceptexecexecfileexitfilefilterfinallyfloatforformatfromfrozensetgetattrglobalglobalshasattrhashhelphexidifimportininputintinternisisinstanceissubclassiterlambdalenlicenselistlocalslongmapmaxmemoryviewminnextnotobjectoctopenorordpasspowprintprintpropertyquitraiserangeraw_inputreducereloadreprreturnreversedroundsetsetattrslicesortedstaticmethodstrsumsupertrytupletypeunichrunicodevarswhilewithxrangeyieldzip
In addition, you should never use a variable name that begins with an
underscore. Although _internal is the only variable in the variable
store that begins with an underscore, the docassemble web app uses
names that begin with underscores to communicate information between
the browser and the server, and if your variable names conflict with
these names, you may experience errors or unexpected results. These
internal names include:
_attachment_email_address_attachment_include_editable_back_one_checkboxes_datatypes_email_attachments_files_question_number_question_name_save_as_success_the_image_track_location_tracker_varnames

