以前のページではユーザ登録検証メールのトークン有効期限を短く変更しました.有効期限が切れてしまった場合は再び送信する必要があります.ここでは検証メールの再送信機能を実装します.
まず URL を定義します.
users/urls.py
from django.urls import path
from . import views
app_name = 'users'
urlpatterns = [
path('', views.users_index, name='index'),
path('<int:user_id>/', views.users_profile, name='profile'),
path('<int:user_id>/update/', views.users_update, name='update'),
path('login/', views.LoginView.as_view(), name='login'),
path('logout/', views.LogoutView.as_view(), name='logout'),
path('password/', views.PasswordChangeView.as_view(), name='password_change_form'),
path('password_change_done/', views.PasswordChangeDoneView.as_view(), name='password_change_done'),
# ユーザ登録
path('create/', views.UserCreateView.as_view(), name='create'),
# メールリンクから呼び出される
path('create/<uidb64>/<token>/', views.creation_confirm, name='create_confirm'),
# 検証メールの再送信
path('create/resend', views.creation_resend, name='create_resend'),
# パスワードリセットのメール送信画面
path('password_reset/', views.PasswordResetView.as_view(), name='password_reset'),
# メール送信後の画面
path('password_reset/done/', views.PasswordResetDoneView.as_view(), name='password_reset_done'),
# メールリンクから呼び出される
path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
path('reset/done/', views.PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]
次に,フォームを設計します.これは同じ forms.py の他のクラスのコードを組み合わせれば大半は記述できます.一部新規に書く必要があります.なお,次の 51〜57 行目はもう少しエレガントなコードにすべきでしょう.
users/forms.py
class UserCreationResendForm(forms.Form):
email = forms.EmailField(
label=_("Email"),
max_length=254,
widget=forms.EmailInput(attrs={"autocomplete": "email",'class': 'form-control'}),
)
def send_mail(
self,
subject_template_name,
email_template_name,
context,
from_email,
to_email,
html_email_template_name=None,
):
"""
Send a django.core.mail.EmailMultiAlternatives to `to_email`.
"""
subject = loader.render_to_string(subject_template_name, context)
# Email subject *must not* contain newlines
subject = "".join(subject.splitlines())
body = loader.render_to_string(email_template_name, context)
email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
if html_email_template_name is not None:
html_email = loader.render_to_string(html_email_template_name, context)
email_message.attach_alternative(html_email, "text/html")
email_message.send()
def get_users(self, email):
email_field_name = UserModel.get_email_field_name()
inactive_users = UserModel._default_manager.filter(
**{
"%s__iexact" % email_field_name: email,
# "is_active": True,
"is_active": False,
}
)
return (
u
for u in inactive_users
if u.has_usable_password()
and _unicode_ci_compare(email, getattr(u, email_field_name))
)
def clean(self):
data = super().clean()
email = data.get('email')
email_field_name = UserModel.get_email_field_name()
users = self.get_users(email)
cnt = 0 # もうちょっとエレガントな方法を使いたい
for u in users:
cnt += 1
if cnt == 0:
self.add_error('email', f'メールアドレスのエラーです"{email}"')
さらに views.py に関数を定義します.
users/views.py
from urllib.parse import urlparse, urlunparse
from django.conf import settings
# Avoid shadowing the login() and logout() views below.
from django.contrib.auth import REDIRECT_FIELD_NAME, get_user_model
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
# from django.contrib.auth.forms import (
# AuthenticationForm,
# PasswordChangeForm,
# PasswordResetForm,
# SetPasswordForm,
# )
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.http import HttpResponseRedirect, QueryDict
from django.shortcuts import resolve_url
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.utils.http import url_has_allowed_host_and_scheme, urlsafe_base64_decode, urlsafe_base64_encode
from django.utils.translation import gettext_lazy as _
from django.utils.encoding import force_bytes
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic.base import TemplateView
from django.views.generic.edit import FormView
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.urls import reverse
from django.contrib import messages
from django.views.generic import CreateView
# from django.shortcuts import redirect
# from django.urls import reverse
from .forms import UserForm
from .forms import AuthenticationForm
from .forms import PasswordChangeForm
from .forms import SetPasswordForm
from .forms import PasswordResetForm
from .forms import UserCreationForm
from .forms import UserCreationResendForm
UserModel = get_user_model()
...(中略)...
def creation_resend(request):
if request.method == 'POST':
form = UserCreationResendForm(request.POST)
if form.is_valid():
user_email = form.cleaned_data.get("email")
current_site = get_current_site(request)
site_name = current_site.name
domain = current_site.domain
user = UserModel._default_manager.get(email=user_email)
token_generator = default_token_generator
use_https = False
extra_email_context = None
subject_template_name = 'users/user_creation_subject.txt'
email_template_name = 'users/user_creation_email.html'
from_email = settings.EMAIL_FROM
html_email_template_name = None
context = {
"email": user_email,
"domain": domain,
"site_name": site_name,
"uid": urlsafe_base64_encode(force_bytes(user.pk)),
"user": user,
"token": token_generator.make_token(user),
"protocol": "https" if use_https else "http",
**(extra_email_context or {}),
}
form.send_mail(
subject_template_name,
email_template_name,
context,
from_email,
user_email,
html_email_template_name=html_email_template_name,
)
messages.success(request, f'メール送信しました {user_email}')
messages.success(request, f'username {user.username}')
return redirect(reverse('index'))
else:
# エラーメッセージをつけて返す
context = {}
context['form'] = form
messages.success(request, 'エラーです.メールアドレスを確認してください')
return render(request, 'users/create_resend_form.html', context)
else:
context = {}
context['form'] = UserCreationResendForm(
initial={}
)
return render(request, 'users/create_resend_form.html', context)
テンプレートを作成します.
users/templates/users/create_resend_form.html
{% extends "base.html" %}
{% block title %}
メール再送信
{% endblock %}
{% block content %}
<h1 class="my-5">コメントアプリケーション</h1>
<div class="card">
<div class="card-header">ユーザ登録検証メールの再送信</div>
<div class="card-body">
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary btn-block">
メールを再送信する
</button>
</form>
</div>
<div class="card-footer">
<p>
</p>
</div>
</div>
{% endblock content %}
ユーザ登録ページに再送信のためのリンクを設置します.
users/templates/users/create_form.html
{% extends "base.html" %}
{% block title %}
ユーザ登録
{% endblock %}
{% block content %}
<h1 class="my-5">コメントアプリケーション</h1>
<div class="card">
<div class="card-header">ユーザ登録</div>
<div class="card-body">
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary btn-block">
ユーザ登録
</button>
</form>
</div>
<div class="card-footer">
<p>
<a href="{% url 'users:create_resend' %}">
Email検証のメールを再送信する
</a>
</p>
</div>
</div>
{% endblock content %}
ユーザ登録ページの最下部に「Email検証のメールを再送信する」リンクが設置されました.
(受信可能な)正しいアドレスを入力してメールを再送信します.
再送信ができたらトップページリダイレクトされます.
再送信のメールからでも検証できることがわかりました.
存在しないメールアドレスではエラーが表示されます.