Dango 2.2 反转'activate'与关键字参数



我在创建帐户并使用电子邮件中发送的链接激活它时遇到问题。该应用程序是用 Django 2.2 版本编写的。

单击激活链接后,我收到一条消息:

Reverse for 'activate' with keyword arguments '{'uidb64': '', 'token': ''}' not found. 1 pattern(s) tried: ['activate/(?P<uidb64>[^/]+)/(?P<token>[^/]+)/$']

urls.py 代码

path('activate/<uidb64>/<token>/', account.activate, name='activate'),

views.py 代码,注册和激活链接的代码。注册就像CBV,激活就像FBV。

class Signup(View):
def get(self, request):
form = SignUpForm()
return render(request, 'account/signup.html', {'form': form})
def post(self, request):
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
current_site = get_current_site(request)
subject = 'Activate your Spotted account'
message = render_to_string('account/account_activation_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user)
})
user.email_user(subject, message)
return redirect('account_activation_sent')
return render(request, 'account/signup.html', {'form': form})

def activate(request, uidb64, token):
try:
uid = force_text(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.profile.email_confirmed = True
user.save()
login(request, user)
return render(request, 'account/account_activation_email.html')
else:
return render(request, 'account/account_activation_invalid.html')

在 account/account_activation_email.html:

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

token.py

from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six

class AccountActivationTokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (
six.text_type(user.pk) + six.text_type(timestamp) +
six.text_type(user.profile.email_confirmed)
)

account_activation_token = AccountActivationTokenGenerator()

如果您使用的是 Django 3.1 或更高版本,激活/密码重置机制对令牌使用 SHA-256 哈希算法。 您的正则表达式太严格了。 根据文档,您应该使用路径而不是 URL,如下所示。

path('reset/<uidb64>/<token>/', ...)
path('activate/<uidb64>/<token>/', ...)

详情请见此处

您必须将tokenuid作为上下文传递给render

def activate(request, uidb64, token):
...
context = {'uidb64':uidb64, 'token':token}
return render(request, 'account/account_activation_email.html', context)

也有同样的问题,我认为与 url 正在寻找的类型存在冲突。为了改变这一点,我只是将网址值更改为字符串或字符串:UUID。

相关内容

  • 没有找到相关文章

最新更新