I need to call an API function after validating a form with is_valid(). This API call can still throw exceptions which in turn may kind of invalidate a field in the form.
How can I do that? I'm looking for something like that:
def smstrade(request):
if request.method == "POST":
form = SomeForm(request.POST)
if form.is_valid():
try:
api_call(...)
except SomeException:
form["field"].set_valid(False)
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.
Form. is_valid () The primary task of a Form object is to validate data. With a bound Form instance, call the is_valid() method to run validation and return a boolean designating whether the data was valid: >>> data = {'subject': 'hello', ... '
{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.
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.
Bit late, but you can invalidate the form and add display the appropriate messages by setting form._errors
>>> f.is_valid()
True
>>> f._errors['my_field'] = ['This field caused a problem']
>>> f.is_valid()
False
>>> str(f)
... <ul class="errorlist"><li>This field caused a problem</li></ul>
I needed to do this with FormView.form_valid()
methods and models with unique fields
def form_valid(self, form):
obj = User(**form.cleaned_data)
try:
obj.save()
except IntegrityError:
form._errors['username'] = ['Sorry, already taken']
return super(MyView, self).form_invalid(form)
return super(MyView, self).form_valid(form)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With