Tuesday, July 31, 2012

How to process form-inputted data in a View -- is_valid() then form.cleaned_data['formfieldname']


https://docs.djangoproject.com/en/1.4/topics/forms/



Processing the data from a form

Once is_valid() returns True, you can process the form submission safe in the knowledge that it conforms to the validation rules defined by your form. 




if form.is_valid():
    subject = form.cleaned_data['subject']
    message = form.cleaned_data['message']
    sender = form.cleaned_data['sender']
    cc_myself = form.cleaned_data['cc_myself']

    recipients = ['info@example.com']
    if cc_myself:
        recipients.append(sender)

    from django.core.mail import send_mail
    send_mail(subject, message, sender, recipients)
    return HttpResponseRedirect('/thanks/') # Redirect after POST



While you could access request.POST directly at this point, it is better to accessform.cleaned_data. This data has not only been validated but will also be converted in to the relevant Python types

data = getattr(request, request.method)
a = data.get('formfieldname')
b = data.get('post_or_get_variable_name')


###############################################

https://docs.djangoproject.com/en/dev/topics/forms/


Processing the data from a form

Once is_valid() returns True, the successfully validated form data will be in the form.cleaned_data dictionary. This data will have been converted nicely into Python types for you.
Note
You can still access the unvalidated data directly from request.POST at this point, but the validated data is better.
In the above example, cc_myself will be a boolean value. Likewise, fields such as IntegerField and FloatField convert values to a Python int and float respectively.
Read-only fields are not available in form.cleaned_data (and setting a value in a custom clean() method won't have any effect). These fields are displayed as text rather than as input elements, and thus are not posted back to the server.
Extending the earlier example, here's how the form data could be processed:
if form.is_valid():
    subject = form.cleaned_data['subject']
    message = form.cleaned_data['message']
    sender = form.cleaned_data['sender']
    cc_myself = form.cleaned_data['cc_myself']

    recipients = ['info@example.com']
    if cc_myself:
        recipients.append(sender)

    from django.core.mail import send_mail
    send_mail(subject, message, sender, recipients)
    return HttpResponseRedirect('/thanks/') # Redirect after POST









No comments:

Post a Comment