Проблема валидации булевых полей в django
похоже, что django плохо обрабатывает ввод с помощью флажка.
В моем приложении необходимо выбрать proceed
или reject
, для этого я использую форму с флажком, событие пользователя обрабатывается javascript.
forms.py
class ActionForm(forms.Form):
action = forms.BooleanField()
class Meta:
fields = ['action']
шаблон
<form id="action-form" style="display: none" method="POST">
{% csrf_token %}
{{ form }}
<button type="submit">submit</button>
</form>
<div id="action-bar">
<button id="reject" class="action-button" type="button">reject</button>
<button id="proceed" class="action-button" type="button">proceed</button>
</div>
javascript
const form = document.getElementById('action-form');
const checkbox = form.querySelector('input');
const reject = document.getElementById('reject');
const proceed = document.getElementById('proceed');
reject.addEventListener('click', ()=>{
checkbox.checked = false;
form.submit();
});
proceed.addEventListener('click', ()=>{
checkbox.checked = true;
form.submit();
});
views.py
def ActionView(request, pk):
if request.method == 'POST':
form = forms.ActionForm(request.POST)
if form.is_valid():
print(form.cleaned_data['action'])
return HttpResponse('')
else:
print(form.errors)
return HttpResponse('')
else:
form = forms.ActionForm()
return render(request, 'template.html', {
'form': form,
})
Результат, который я получил
<ul class="errorlist"><li>action<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
Что я пробовал:
add
required=False
to theBooleanField
, the result sent was alwaysFalse
even if I click onproceed
add
initial=True
to theBooleanField
, the result sent was always what the initial is.add both, the result sent was always
False
Я буду очень благодарен за ваше предложение