[英]Cancel the POST when the page is refreshed
My problem is: when an user refresh a form, the data in the Form
is sent. 我的问题是:当用户刷新表单时,将发送Form
的数据。
I have a Form
with a POST
request. 我有一个带有POST
请求的Form
。
The user writes his name, mail and a message. 用户写下他的名字,邮件和消息。 If the mail is correct, the message is sent. 如果邮件正确,则发送邮件。
In my view, if the Form
is valid, I add the message in my model Message. 在我看来,如果Form
有效,则将消息添加到模型消息中。
After that I disable the "Send" button. 之后,我禁用“发送”按钮。 But if the user refreshes the page, my view is called, and another row is added in my model. 但是,如果用户刷新页面,则会调用我的视图,并在模型中添加另一行。
I would like, when the user refreshes the page, to block the POST. 我想在用户刷新页面时阻止POST。
My View: 我的观点:
def contact(request):
form = MessageForm(request.POST or None)
if form.is_valid():
name = form.cleaned_data['name']
message = form.cleaned_data['message']
mail = form.cleaned_data['mail']
new_message = Message()
new_message.name = name
new_message.message = message
new_message.mail = mail
new_message.save()
envoi = True
return render(request, 'vautmieux/contact.html', locals())
My URL: 我的网址:
path('contact/', views.contact, name='contact'),
My HTML: 我的HTML:
<form action="{% url "contact" %}" method="post">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
{{ form.name }}
{{ form.mail }}
</div>
<div class="col-md-6" >
{{ form.message }}
</div>
<button id="sendMessageButton" type="submit">ENVOYER LE MESSAGE !</button>
</div>
{% if envoi %}Votre message a bien été envoyé !{% endif %}
</form>
This is the main reason why people implement the Post/Redirect/Get pattern [wiki] . 这是人们实现Post / Redirect / Get模式[wiki]的主要原因。 In case of a successful POST request, you should return a redirect to a URL. 如果POST请求成功 ,则应将重定向返回到URL。 As a result the browser will perform a GET, and in case the browser thus performs a refresh later, it will make a GET again. 结果,浏览器将执行GET,并且如果浏览器随后执行刷新,则它将再次进行GET。
def contact(request):
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
form.save()
return redirect('some-message-successful-view')
else:
form = MessageForm()
return render(request, 'vautmieux/contact.html', {'form': form})
Here 'some-message-successful-view'
needs to be replaced with the name of a view you trigger when sending a message was succesful. 在这里, 'some-message-successful-view'
需要替换为在发送消息成功时触发的视图名称。 This can be the same view as the one defined here. 该视图可以与此处定义的视图相同。 I advice to use Django's message framework [Django-doc] to send a message to the user that the message has been submitted successfully. 我建议使用Django的消息框架 [Django-doc]向用户发送消息,表明该消息已成功提交。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.