2π
validation and execution
No execution or stateful changes in the form clean()
. Please. The formβs clean()
should only mess with data on the form, not anywhere else.
If there is a stateful change, it must be in a view function inside a non-GET request handler.
0π
I usually encapsulate these type of logic in the form. Since you use the form to validate the data you also use it to send the data. This makes sense because the form already knows about the data and its types etc (it has the cleaned_data
dictionary).
But processing data and changing state of your application should not live directly inside your validation logic (e.g. in your clean
method). You should put it in an extra method of your form β like ModelForm
is doing it with the save()
method.
So my suggestion is to have an extra method named save()
(if the method actually saves your processing to the REST service) or post_result()
or something similar that fits better.
Here is an example:
# forms.py
class ValidateDataForm(forms.Form):
...
def clean(self):
# validation logic
def save(self):
post_results_to_service(self.cleaned_data)
# views.py
def view(request):
if request.method == 'POST':
form = ValidateDataForm(request.POST)
if form.is_valid():
form.save()
else:
form = ValidateDataForm()
The above assumes that the REST service is changing state for your
application, e.g. it implements some business logic. If this is not the case
and you only use the service as validation for the input data on your form β
and use the form data then for something different β I would suggest something
different.
In this case the code should go into the clean()
method like you suggested
in your second code example.
- [Answered ]-How do I open this JSON data with Python?
- [Answered ]-Django-autocomplete-url invalid URL
- [Answered ]-How do I merge two django db's?
- [Answered ]-Debugging broken connection with EC2, Ubuntu, & Django