What does clean mean in Django? - python

This is an obvious question for everyone, but I don't understand what the term "clean" means. I can use clean_data, and use form validation on my forms. However, I still don't understand what this means.
In order to use validation, do I always need to use the keyword "clean"?

As stated in documentation
The clean() method on a Field subclass is responsible for running
to_python(), validate(), and run_validators() in the correct order and
propagating their errors. If, at any time, any of the methods raise
ValidationError, the validation stops and that error is raised. This
method returns the clean data, which is then inserted into the
cleaned_data dictionary of the form.
Clean is preventing dirty data in DB

As far as i have understood ..all the implicit validations are performed using clean..
which is performed when we check for the form validity using is_valid:
but we can add our own validations to it by overriding the function clean():
what we have to do is we call the super().clean() such that all the implicit validations are done by the clean() defined by django and then add our own validations to it if necessary...
when you call the super().clean() it returns the dictionary containing the cleaned_data..
you can store it in a variable ...
or else you can access the dictionary using self.cleaned_data

Related

How can I produce a warning with ceberus if a key is missing?

Cerberus allows for required fields but I'd like to have a "preferred" class of fields such that a warning message is logged if they're missing. Some ideas I have that don't seem great are the following:
I could extend the validator with a custom rule, but these are called with field and value arguments, making me suspect that this function would be called on missing fields. __validate_required_fields which is called on the document to generate missing fileds would be more ideal, but I'm not sure how to hook that in.
Cerberus offers a check_with option but again, I'm not sure if this would be called on missing fields.
I could try to mark these as required and do the tracing in an error handler. This is not ideal because validation should not fail if "preferred" fields are missing.
Your suspicion is correct, fields that are not in the document are not validated fully. And __validate_required_fields isn't designated to be overridden (name mangling would fail due to two leading __).
It is not as in 1.
That would best be done by overriding the validate method and post-process the various (!) error containers.
I think the simplest solution would be to validate against two different schemas, one that checks hard and one that you get the warnings from.

Is there any relationship between model's clean() method and form's clean() method?

I have overwritten clean() methods for some of my models to construct constraints to meet my DB schema requirements (Because it required runtime information for those validations).
Since now I have finished most of the back-end side components(models, signals, ..) now I'm trying to write ModelForms for my models.
What I'm wondering is that, is there any relationship between the clean() method of model and clean() implementation on the form side?
If so and form's clean() calls model's clean() I won't have to rewrite my model - side clean() implementation and be able to avoid code redundancy.
Yes, ModelForm cleaning involves model cleaning. That's the idea with a ModelForm: there are a lot of useful defaults that can be determined by auto building a form object from a model.
I've discovered this clean chaining through personal experience, but to back it up I can reference the source.
On 1.8, ModelForms call the model instance full_clean method. On 1.7, it calls the clean method directly.
Form.full_clean()
def full_clean(self):
# ..... snip
self._clean_fields()
self._clean_form()
self._post_clean()
ModelForm._post_clean for 1.8
Model full_clean() calls clean() amongst other validation: https://docs.djangoproject.com/en/1.8/ref/models/instances/
self.instance.full_clean(exclude=exclude, validate_unique=False)
ModelForm._post_clean for 1.7
self.instance.clean()
According to Model.clean and ModelForms clean, I don't think there is any relationship between them.
These two clean has the same name but they did a different job.
Model.clean is used to validate the data you are going to store into database, and make sure the data is ok and can be stored into database.
This method should be used to provide custom model validation, and to modify attributes on your model if desired.
ModelForms clean, by my understanding, is to validate what the user has entered, and make sure they are ok.
You can override the clean() method on a model form to provide additional validation in the same way you can on a normal form.
And on a normal form, it's:
Implement a clean() method on your Form when you must add custom validation for fields that are interdependent.
And I think this one is also what you wanted:
Notice that we are talking about the clean() method on the form here, whereas earlier we were writing a clean() method on a field. It’s important to keep the field and form difference clear when working out where to validate things. Fields are single data points, forms are a collection of fields.

How to use full_clean() for data validation before saving in Django 1.5 gracefully?

I think Django's model validation is a little inconvenient for those models that don't use built-in ModelForm, though not knowing why.
Firstly, full_clean() needs called manually.
Note that full_clean() will not be called automatically when you call
your model’s save() method, nor as a result of ModelForm validation.In
the case of ModelForm validation, Model.clean_fields(), Model.clean(),
and Model.validate_unique() are all called individually.You’ll need to
call full_clean manually when you want to run one-step model
validation for your own manually created models.
Secondly, validators are used in built-in ModelForm.
Note that validators will not be run automatically when you save a
model, but if you are using a ModelForm, it will run your validators
on any fields that are included in your form.
There are great demands when you need to do data validation before saving data into databases. And obviously I'd prefer to make it in model, rather than views. So, are there any good ideas to implement this gracefully in Django 1.5?
Even though the idea of enforcing validation on Model level seems right, Django does not do this by default for various reasons. Except for some backward-compatibility problems, the authors probably don't want to support this because they fear this could create a false feeling of safety when in fact your data are not guaranteed to be always validated. Some ORM methods (e.g. bulk_create or update) don't call save() and thus are unable to validate your models.
In other words, it is hard to guarantee the validation, thus they've decided not to pretend it.
If you need this for multiple models, you can create a simple mixin that overrides the save() method and calls full_clean() before super. Do note that this might cause the validation to be run twice in some cases, like when using ModelForm. It might not be that of an issue though if your validation routines are side-effect free and cheap to run.
For more info, please see these answers:
https://stackoverflow.com/a/4441740/2263517
https://stackoverflow.com/a/12945692/2263517
https://stackoverflow.com/a/13039057/2263517

Design of CBVs in Django

I'm currently trying to get into "Class Based Views" with Django 1.5.
From the design perspective i wonder where to put the logic to process data comming from a form in a simple FormView.
I know that all form validation code comes into the method form_valid(). But where to put things which processes data of the form. I read that its somehow inappropriate to put too much logic into the form_valid() method.
There are the get(), post(), get_context_data(), head(), etc. methods... which should I use in which case?
Form validation, data cleaning, etc goes with the form class in the clean methods
Processing of a valid form should go in an overridden form_valid method
That's it! If your use-case is more complicated you can call out to other methods of your creation from form_valid...
Any answer to this question is open for discussion. That said, views are just Python classes, so you could overwrite any method to customize things accordingly.
It is also perfectly legit to create an extra method on your class to handle data processing.

how to display error message in save method of django

I want to display error message in case the instance I am creating is more than the maximum limit I have specified in a certain model. This is a inner condition.
I know that we can hide the + and override the has_add_permission method. This is used for user authentication in my application.
However, I wish to allow the instance to be created for a certain login who is a superuser based on the inner condition.
ValidationError gives me error u' max...' ValidationError at the url...
Can anyone guide?
I don't know what an "inner condition" is.
However, you don't do this in the save method. You do it in a validator. For instance, you could define a clean method on your model to handle this, or use a custom form with the validation in.

Categories

Resources