使用 Django 的用户帐户激活电子邮件



我正在尝试创建用户注册表。用户帐户将通过激活电子邮件激活。 以下错误即将到来:-

异常类型:NoReverseMatch at/register/异常值:未找到"激活"的反向。"激活"不是有效的视图函数或模式名称。

我点击了以下链接:

https://studygyaan.com/django/how-to-signup-user-and-send-confirmation-email-in-django

https://blog.hlab.tech/part-ii-how-to-sign-up-user-and-send-confirmation-email-in-django-2-1-and-python-3-6/

https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef

def register(request):
if request.method == 'POST':
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
current_site = get_current_site(request)
mail_subject = 'Activate your blog account.'
message = render_to_string('website/acc_active_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user=user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return HttpResponse('Please confirm your email address to complete the registration')
else:
for msg in form.error_messages:
print(form.error_messages[msg])
else:
print('in else')
form = NewUserForm()
return render(request=request, template_name='website/register.html', context={'form': form})
def activate_account(request, uidb64, token):
try:
uid = force_bytes(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
login(request, user)
return HttpResponse('Your account has been activate successfully')
else:
return HttpResponse('Activation link is invalid!')

我的 html 文件代码

{% autoescape off %}
Hi {{ user.username }},
Please click on the link to confirm your registration,
http://{{ domain }}{% url 'activate' uidb64=uid token=token %}
{% endautoescape %}

引发错误的代码部分似乎丢失。

异常类型:NoReverseMatch at/register/异常值:反向 未找到"激活"。"激活"不是有效的视图功能或 模式名称。

此错误表示您的 urls.py 中没有 name='activate '的 url。

在 django 2.x 中,它应该看起来像:

urlpatterns = [
#...
path('/register/', activate_account, name='activate'),
#...
]

在 django 1.x 中,它应该看起来像:

urlpatterns = [
#...
url(r'^register/$', activate_account, name='activate'),
#...
]

正如 django 手册中所写的那样,您必须给 url 一个名称才能使用 reverse(( 查找来访问它。

相关内容

  • 没有找到相关文章

最新更新