what's the difference between cleaned_data and normal data? - django - python

as mentioned in title...what's the difference?
I have seen people keep on saying use cleaned_data and in videos people still say so but only says it cleans the data but when I use print
print form.cleaned_data.get('title')
print request.POST.get('title')
I don't see any difference though. At first I thought it's those character escape and so but tested and doesn't seem so.
which is actually a preferred way since there doesn't seem to have differences?

You can not trust on request data as it is raw data which are not validated. You should never use data from request and store it to your database.
It so important that you store only valid data in database for smooth functioning of application. Django forms cleaned_data ensure you that validation rules defines for that form are satisfied or not. form.is_valid() check all your validations against request.POST data and generate dictionary containing valid data which is form.cleaned_data.
So data retrieved from forms.cleaned_data attribute are go through form validation. It's not only validation but also converted data to relevant python type too.
You can also refer this link to know how Django form perform validation.

Related

Return django validation errors in JSON format

Suppose I am building a registration/signup or any form in general for my web app in Django and I want the same form for Web/Android/IOS. So I want the frontend and backend(Django) to communicate via JSON. My question is how can I send validation errors in JSON format if the user on any platform(Web/Android/IOS) gives me invalid data like "the email already exists" type of errors?
I need the best way possible to handle this type of scenarios and well-detailed example/explanation will be much appreciated.
Thank You.
The form's errors attribute has an as_json method you can use.
if form.is_valid():
# process valid form
else:
errors_json = form.errors.as_json()
...
Note the warning in the docs about escaping the errors to avoid cross site scripting attacks.

Django - how to save form without validation?

I need to separate form saving feature from form confirming. I want to give user possibility to save form without validating its content firstly, but when form is finished, users should click confirm button which implies data validation and saves it to database.
When I try to save it with commit=False parameter it raises error:
The Table could not be created because the data didn't validate.
UPDATE:
What I did was delete validation in model and create different function with validation which is executed when user finished with form. So I dont validate this form in Django terms.
But if somebody got different solution please answer.
in forms.py, you need to specify that all field is not required, pass required=False to the Field constructor:
example:
first_name = forms.CharField(max_length = 150, required=False)
I had the same issue. The solution I ended up with was using two tables:
one for unconfirmed data (contains data in JSON format and boolean field is_confirmed)
one for confirmed data
If your database supports JSON data type(for example MySQL 5.7+), you can stick with only former table.
I think that's better because validation is not only about required fields. Just imagine a user typed invalid date in a date field. If you save it without validation, it will be saved to db as NULL (or 0000-00-00). So, the original invalid value will be lost.

How can I submit a Django formset within python code?

Background. We want our users to check if the metadata we read out of several images is correct.
Therefore, we show the retreived data in a formset to let the user check everything.
In case the metadata has errors (that happens) we would like to display them as form errors here.
Problem. To obtain the error messages we need bound forms. Feeding our various data into a bound ModelFormSet and taking care of the ManagementForm is ... not so simple. With the unbound version everything works fine.
Idea. If we could produce an unbound form and submit it within the python code, that would be a simple way to get the POST data we need to create the bound form.

Django - saving fields in invalid form submissions

What is the recommended way of handling a "save"-style form submission (created from a ModelForm) when:
A non-empty subset of the form's fields validate
A non-empty subset of the form's fields do not validate
I want to save the subset of fields that are valid to the instance in question, and not the invalid ones.
I'm fairly sure I could write the code to do this but as with much of Django I'm sure there's a "normal"/"recommended" way of solving this, or some pattern I can follow.
All advice much appreciated.
You will need to provide your own clean method to deal with the non-validating fields, and prevent cleaned_data being clobbered.
You will need to also provide your own save method which knows to only save the right fields.

Where to store field data and how to provide access to it?

Forms have Fields, Fields have a value. However, they only get a value after the form has been submitted.
How should I store this value? Should I give every field a value attribute, field.value,
leave it as None prior to posting, and fill it in afterwords?
Omit it completely, and dynamically add it?
Store it on the form instead, like form.data['field'].
Create a a wrapper class FieldWithData to avoid any inconsistent states (if you have an object of this type, you know it has data) and allows me to set the data in the initializer rather than accessing attributes directly (although I guess this isn't so different from using a setter)
How should I provide access to the field data through the Form object? Options:
form.fields['name'].value (how it's presently being stored internally)
form.data['field'] (create a proxy "data" class that retrieves the real data off the field, or re-arrange the internals to actually store the data like this)
form.field.value - looks fairly nice, but then I'd have two references to the same field, one as form.field and one as form.fields['field'] which I need internally so that I can iterate over them
Too many design decisions. Driving me nuts. This is what sucks about solo'ing a project.
It really depends on how you interact with the structures in question. Do you manipulate Form and Field objects prior to assigning them values? Do you need to frequently iterate over all the given Fields? Do you need Form once it's been submitted? Etc.
I'd suggest writing some/all of the code that uses Form and figure out how you want to interact with Form data, and what your ideal interface would look like.
I would keep a form's definition and the form's values from submission separate. I.e. I would not have a value attribute on the Field(Definition) objects.
To work with submitted values, I would probably use a dict. You could let the Form class handle the creation of this dict:
# assuming my_form is a Form object and request represents the HTTP request
form_values = my_form.values_from_request(request)
print(form_values["Name"])
The values_from_request method would iterate through the Form's Field(Definition)s to get the submitted data from the HTTP request. The method could also do stuff like validation and data type conversion.

Categories

Resources