在个人资料页面的自定义模板中,我使用此表单重新发送验证电子邮件:
{% extends "main/base.html" %}
{% load static %}
{% load account %}
{% block title %}Home{% endblock %}
{% block body %}
<p>Username: {{user.username}}</p>
<p>Email: {{user.email}} {% if emailadress.verified %}(Verified){% endif %} (Unverified)</p>
<form action="/accounts/email/" method="post">
{% csrf_token %}
<input style="display:none" type="text" name="email" value="{{user.email}}" readonly>
<button class="btn-auth" type="submit" name="action_send">Resend Verification</button>
</form>
{% endblock %}
此表单是从位于 /accounts/profile/
的视图提交的,但在提交时,会将用户重定向到 /accounts/email/
。我查看了 allauth 的源代码,但我无法理解重定向 URL 是如何确定的。我尝试在表单中添加一个 next
值,但这没有任何作用。有没有办法在重新发送验证后指定要重定向到的 URL,还是应该将 /accounts/profile/
模板移至 /accounts/email/
?
答案 0 :(得分:2)
1. EmailView
(django-allauth) 也支持 AJAX 请求。
所以你可以简单地使用 jQuery 发出 AJAX 请求:
<div class="container">
<form action="{% url 'account_email' %}" method="post" name="resendVerification">
{% csrf_token %}
<input style="display:none" type="text" name="email" value="{{user.email}}" readonly>
<button class="btn-auth" type="submit" name="action_send">Resend Verification</button>
</form>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('form[name="resendVerification"]').submit(function(e) {
// avoid to execute the actual submit of the form.
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serialize data
success: function(data) {
// show response from django allauth
alert("We have sent an e-mail to you for verification to " + data.data[0].email);
}
});
});
</script>
2. 或者您也可以写一个 simple view 重新发送电子邮件验证,将您重定向到所需的网址 - redirect("/accounts/profile/")
:
views.py:
from allauth.account.models import EmailAddress
from allauth.account.adapter import get_adapter
from django.contrib import messages
from django.shortcuts import redirect
def resend_verfication(request):
if request.method == "POST":
email = request.POST["email"]
try:
email_address = EmailAddress.objects.get(
user=request.user,
email=email,
)
get_adapter(request).add_message(
request,
messages.INFO,
"account/messages/" "email_confirmation_sent.txt",
{"email": email},
)
email_address.send_confirmation(request)
except EmailAddress.DoesNotExist:
pass
# redirect("named_url") or even better use here named url
return redirect("/accounts/profile/")
urls.py:
from django.contrib.auth.decorators import login_required
urlpatterns = [
...
path('profile/resend-verfication/', login_required(views.resend_verfication), name="myapp_resend_verfication"),
...
]
然后在您的表单中作为操作使用 {% url 'myapp_resend_verfication' %}
:
<div class="container">
<form action="{% url 'myapp_resend_verfication' %}" method="post">
{% csrf_token %}
<input style="display:none" type="text" name="email" value="{{user.email}}" readonly>
<button class="btn-auth" type="submit" name="action_send">Resend Verification</button>
</form>
</div>