I came here for this because I’m not sure if it’s the javascript at fault or something in my view or html. What the code is supposed to do is to change the value of the hidden input when the additems button is clicked. That refreshes the page and adds 2 more forms to the page. But for some reason, the additems if statement never triggers, it skips to else.
EDIT: I was able to figure out that the if statement does trigger if I remove the “and request.POST[‘additems’] == ‘true’” portion, so additems is in request.POST, but it’s not evaluating == ‘true’
#views.py
@ensure_csrf_cookie
def gallery_editor(request):
extra_forms = 2
ArtFormSet = formset_factory(ArtForm, extra=1, max_num=20)
if request.method == 'POST':
if 'additems' in request.POST and request.POST['additems'] == 'true':
formset_dictionary_copy = request.POST.copy()
formset_dictionary_copy['form-TOTAL_FORMS'] = int(
formset_dictionary_copy['form-TOTAL_FORMS']) + extra_forms
formset = ArtFormSet(formset_dictionary_copy)
context = {
'formset': formset,
}
return render(request, 'editors/gallery_editor.html', context)
else:
formset = ArtFormSet(request.POST)
if formset.is_valid():
context = {
'uploaded': True,
'formset': formset,
}
return render(request, 'editors/gallery_editor.html', context)
else:
formset = ArtFormSet()
context = {
'formset': formset
}
return render(request, 'editors/gallery_editor.html', context)
#addItems.js
$(document).ready(function() {
$("#additemsbutton").on('click',function(event) {
$("#additems").val("true");
});
});
#gallery_editor.html
<body>
<header>
{% include 'home/mobile_nav.html' %}
{% include 'home/desktop_nav.html' %}
{% include 'editors/admin_nav.html' %}
</header>
<main>
{% if uploaded %}
<p style="color: green">Successfully uploaded.</p>
{% endif %}
<form method="post" action="">
{% csrf_token %}
{{ formset.management_form}}
{% for form in formset %}
<div>{{ form }}</div>
{% endfor %}
<input type="hidden" value="false" name="additems" id="additems">
<button class="btn btn-primary" id="additemsbutton">Add items</button>
<input type="submit" value="Submit order" class="btn btn-primary">
</form>
</main>
<footer>
{% include 'home/footer.html' %}
</footer>
<!-- Javascript -->
<script src="{% static 'editors/js/addItems.js' %}" />
</body>