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.)
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})
- What does "Directory indexes are not allowed here." mean in a Django error?
- How to download a filefield file in django view
- Overriding Size of Django Admin Multi-select Widget
- Annotate django query if filtered row exists in second table