我正在尝试创建“用户注册”表单。用户帐户将通过激活电子邮件激活。 出现以下错误:-
异常类型:/ register /处的NoReverseMatch异常值:找不到“激活”的反向。 “激活”不是有效的视图函数或模式名称。
我关注了以下链接:
https://studygyaan.com/django/how-to-signup-user-and-send-confirmation-email-in-django
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 %}
答案 0 :(得分:0)
引发错误的代码部分似乎丢失了。
异常类型:/ register /处的NoReverseMatch异常值:反向 找不到“激活”。 “激活”不是有效的视图功能,或者 模式名称。
此错误表明您的urls.py中没有名称为'activate'的网址。
在django 2.x中,其外观应为:
urlpatterns = [
#...
path('/register/', activate_account, name='activate'),
#...
]
在Django 1.x上,它应该像这样:
urlpatterns = [
#...
url(r'^register/$', activate_account, name='activate'),
#...
]
按照django manual的规定,您必须给URL指定一个名称,以便通过reverse()查找来访问它。