我有一个表单的Django视图,它向用户展示了两个选项。在表单提交时,一个按钮将它们发送到一个视图,另一个将它们发送到另一个视图。这是视图的一部分:
form = MenuItemForm(request.POST or None, request.FILES or None)
if request.method != 'POST':
# No data submitted; create a blank form.
form = MenuItemForm()
else:
if 'add_ingredients' in request.POST:
# POST data submitted; process data.
if form.is_valid():
menu_item = form.save(commit=False)
menu_item.menu = menu_instance
menu_item.save()
return redirect('core:add_ingredient', menu_item_id=menu_item.id)
else:
# POST data submitted; process data.
if form.is_valid():
menu_item = form.save(commit=False)
menu_item.menu = menu_instance
menu_item.save()
return redirect('core:edit_menu')
它自己工作得很好。下面是模板中的表单和按钮:
<form id="form" class="form" method="post" action="{% url 'core:add_ingredient' menu_item.id %}">
{% csrf_token %}
{{ form.as_p }}
<div class="button-container">
<button id="another-ingredient-button" type="submit" name="add_ingredient">Add Another Ingredient</button>
<button type="submit" name="substitute">Add Substitute</button>
<button class="done" type="submit" name="done">Done</button>
</div>
</form>
在我添加了下面的代码之后,表单仍然提交,但是它不能识别哪个按钮被点击提交了表单,并且总是将我发送到一个视图,我想给每个按钮添加一个eventListener,但是然后我的警告框和其他代码即使在表单不提交时也会运行。任何帮助将不胜感激!
const alertBox = document.getElementById('alert-box')
const anotherIngredientButton = document.getElementById('another-ingredient-button')
const form = document.getElementById('form')
let formSubmitted = false;
form.addEventListener('submit', (e) => {
e.preventDefault()
alertBox.style.display = 'block';
console.log(form)
setTimeout(() => {
form.submit()
alertBox.style.display = 'none'
formSubmitted = true
}, 1000)
});
你可以给你的按钮添加一个value
属性:
<button type="submit" name="button_type" value="add_ingredient">Add Another Ingredient</button>
<button type="submit" name="button_type" value="substitute">Substitute</button>
<button type="submit" name="button_type" value="done">Done</button>
和你的view
:
if request.POST.get("button_type") == "add_ingredient":
...
elif request.POST.get("button_type") == "substitute":
...
elif request.POST.get("button_type") == "done":
...