Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get errors from client post method in django testing

Is there a quick way to get the errors from a form submission when using Client in a django test?

Here's a code snippet:

with open(good_path) as fp:
            data = {
                'account': account_id,
                'date': date,
                'file': fp
            }
            response = client.post(reverse('myapp:form-page'), data)

The page is not redirecting correctly (response=200) and I can see in response.content that there is an error being returned.

Is there a quick way to isolate the error? I was hoping for something like response.errors, similar to a forms instance.

like image 936
Ryan Skene Avatar asked Sep 09 '26 07:09

Ryan Skene


1 Answers

Assuming the underlying view uses a template to render its response, you can access the context of that template using response.context. So, for example, if your view does something like this:

form = MyForm(request.POST)
if form.is_valid():
    return redirect(...)
return render(request, 'template.html', {'form': form})

your test can access response.context['form'].errors to see the form errors.

like image 138
Daniel Roseman Avatar answered Sep 10 '26 22:09

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!