I have a form ‘in the wild’ that takes many different variables – which may or may not be populated.
try:
app_version = request.REQUEST["appVersion"]
except:
app_version = ''
try:
app_name = request.REQUEST["appName"]
except:
app_name = ''
try:
app_code_name = request.REQUEST["appCodeName"]
except:
app_code_name = ''
Is there a tighter way to accomplish this?
If these variables are intended to populate a form, then you can safely pass the
request.POSTobject directly into the form constructor.The form will automatically pass the correct values to the correct form fields
and use defaults for keys that don’t existand will still create blank fields for missing keys (see addendum).If you are trying to process a form, it is still better to create a form object as above, and read out the values from that object.
Remember, validation code is best placed in the form class as well. That way, if
form.is_valid()returnsTrue, then you know you have a clean dataset to work with.Note: Django docs recommend using
request.POSTorrequest.GETdirectly rather than the amalgamated variablerequest.REQUEST, as it is more explicit.Addendum:
It is important to understand the difference between bound and unbound forms in this case. If you create an unbound form with
form = MyForm(), then when the form is instantiated, it will fill in all fields with theinitialproperty of each field (if it exists). For example, with this code:the form will be initialized with appVersion having a value of ‘1.0’. However, if you bind a POST request to a form like this:
form = MyForm(request.POST), then the initial properties are ignored. That means if the POST dict does not include an appVersion key, then that field will be left blank. As long as the field is not required, your form will still validate, and you can modifyform.appVersionin the view after validation.