[Fixed]-Django form.is_valid() always false

19πŸ‘

βœ…

It turns out that Maxime was right after all (sorry) – you do need the data parameter:

form = AuthenticationForm(data=request.POST)

The reason for that, though, is that AuthenticationForm overwrites the signature of __init__ to expect the request as the first positional parameter. If you explicitly supply data as a kwarg, it will work.

(You should still leave out the else clause that redirects away on error, though: it’s best practice to let the form re-render itself with errors in that case.)

12πŸ‘

Check out form.errors which will help you find out why.

πŸ‘€Zhuo.M

0πŸ‘

If situation arises, that you don’t have an option (I was trying to work with bootstrap modals and it was just not working), I had to do this, or else the modal would always trigger even if the form had not issues (and the is_valid is always False by default)

What I needed:

  • Show modal when I click a button
  • if errors, show on the same page, the modal, with the error.

In the modal template:

{% if not brand_form.is_valid and brand_form.errors %}
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
        <script type="text/javascript">
             $(window).on('load', (function() {
                $('#brandAddModal').modal('show');
             }));
        </script>
                    
          {{ brand_form.non_field_errors }}
{% endif %}

In the view:

def add_brand_form(request):
    form = BrandForm()
    if request.method == 'POST':
        form = BrandForm(data=request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/home')
        else:
            return render(request, template_name='home.html', context={'brand_form':form})
        
    return render(request, template_name='modal_add_brand.html', context={'brand_form':form})

Leave a comment