Django 更改表单是否有任何简单的方法可以在提交后禁用按钮。我想防止用户同时提交两次表单!
为了防止用户在 Django 中多次提交表单,您可以在单击提交按钮后禁用该按钮。 这是避免重复表单提交的常见方法。 您可以结合使用 Django 来处理表单和 JavaScript 来管理按钮状态来实现此目的。
🥇这是一个基本示例来说明这一点:
💨第 1 步:创建 Django 表单
首先,在 forms.py 文件中创建一个 Django 表单。
例如:👇
from django import forms
class MyForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
💨第2步:创建一个视图来处理表单提交
在你的views.py中,你将处理表单提交:👇
from django.shortcuts import render
from .forms import MyForm
def my_view(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
# Process the form data
# Example: save it to the database
# form.save()
# Redirect or show a success message
return render(request, 'success.html')
else:
form = MyForm()
return render(request, 'form_template.html', {'form': form})
💨第3步:创建模板
在您的模板中,您将包含表单并添加 JavaScript 以在提交后禁用该按钮。
例如在form_template.html中:👇
<!DOCTYPE html>
<html>
<head>
<title>Form Example</title>
</head>
<body>
<form method="post" id="my-form">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" id="submit-button">Submit</button>
</form>
<script>
document.getElementById('my-form').onsubmit = function() {
document.getElementById('submit-button').disabled = true;
}
</script>
</body>
</html>
🛠说明:
⚡表单提交:表单使用POST方式提交。
⚡CSRF 令牌:确保在 Django 中包含 {% csrf_token %} 以实现 CSRF 保护。
⚡JavaScript:JavaScript 代码监听表单的 onsubmit 事件。当表单提交时,它通过将其disabled属性设置为true来禁用提交按钮。
⚡其他注意事项:
✔Error Handling: If there’s a validation error, you might want to handle re-enabling the button. However, in this simple example, the page reload will naturally reset the button state.
✔User Experience: Optionally, you can add styles to indicate to the user that the button is disabled, such as changing its appearance or using a loading spinner.
此方法可确保按钮在单击后立即被禁用,从而防止重复的表单提交。