Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use the text from request.POST or form.cleaned_data

It might sound like a trivial question, but this is quite a battle to me.

For a form, and hit submit, should one uses form.cleaned_data to access the form data, or look up in request.POST?

The only thing that people usually do with request.POST is look up the submit button. But if I created a submit button as a widget, I can also look it up in form.cleaned_data. The thing is, what about other form data? They are lookup-able in request.POST as well.

Thanks.

like image 557
user1012451 Avatar asked Dec 20 '22 21:12

user1012451


2 Answers

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

like image 192
Vivek S Avatar answered Dec 28 '22 08:12

Vivek S


You can do for example:

class YourForm(forms.Form):
    test = forms.CharField(label='A test label', widget=forms.Textarea(attrs={"placeholder":"Your Placeholder", "rows":6, "cols":45}), max_length=150)


if request.method == "POST":
    form = YourForm(request.POST)
    if form.is_valid():
        cleaned_test = form.cleaned_data["test"]
like image 38
Registered User Avatar answered Dec 28 '22 07:12

Registered User