Set django as erroneous after is_valid ()

I need to call an API function after validating a form using is_valid (). This API call can still throw exceptions, which in turn can somehow invalidate the field in the form.

How can i do this? I am looking for something like this:

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) 
+4
source share
4 answers

Itโ€™s better to override the clean method for the field you are interested in and add your own logic there. Thus, you can also display the corresponding error message.

+3
source

The bit is late, but you can cancel the form and add the display of the corresponding 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 using 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) 
+4
source

It looks like you just need a variable to hold a valid state outside the form object.

 def smstrade(request): if request.method == "POST": form = SomeForm(request.POST) valid = form.is_valid() if valid: try: api_call(...) except SomeException: valid = False if valid: # still valid? print "VALID!" 

But it really seems that you should put this on the form, so you only need to call is_valid() once. The only complication would be if you needed access to the request object.

 class MyForm(forms.Form): def clean(self): cd = super(MyForm, self).clean() try: api_call except Exception: raise forms.ValidationError("API Call failed") return cd # view.. if form.is_valid(): print "api call success and the rest of the form is valid too." 
+1
source

If you really want to activate form validation by calling is_valid second, then you can do it (Django 1.4)

 form = MyForm(data) form.is_valid() # ... form._errors = None form.is_valid() # trigger second validation 
0
source

Source: https://habr.com/ru/post/1412653/


All Articles