Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set django form as erroneous after is_valid()

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)
like image 497
Strayer Avatar asked May 15 '12 19:05

Strayer


People also ask

What is form Is_valid () in Django?

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.

What is form Is_valid ()?

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', ... '

What is form as_ p in Django?

{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.

What does clean do Django?

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.


1 Answers

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)
like image 92
Tris Avatar answered Sep 20 '22 00:09

Tris