使用 uid/token 变量呈现电子邮件模板时没有反向匹配

No reverse match when rendering an email template with uid/token variable

我写了一个用户注册视图,包括电子邮件验证。但是,一旦视图尝试呈现邮件模板,它就会因以下错误而中断。

我什至不明白错误本身。见解将不胜感激。根据一些谷歌搜索,可能 uid 不是字符串?

NoReverseMatch at /signup/ Reverse for 'activate' with keyword arguments '{'uidb64': 'MTE', 'token': 'asnwwr-550108ae10aa04da212561866c8d1ae3'}' not found. 1 pattern(s) tried: ['activate/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$']

邮件模板

{% autoescape off %}
Hi {{ user.username }},

Please click on the link below to confirm your registration:

http://{{ domain }}{% url 'activate' uidb64=uid token=token %}
{% endautoescape %}

查看

def signup(request):
    if request.method == 'POST':
        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 Poller Account'
            message = render_to_string('userprofile/account_activation_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),   # Issue might sit here?
                'token': account_activation_token.make_token(user),
            })
            user.email_user(subject, message)
            return redirect('account_activation_sent')

令牌

from django.contrib.auth.tokens import PasswordResetTokenGenerator
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.email_confirmed)
        )

account_activation_token = AccountActivationTokenGenerator()

Url

url(r'^account_activation_sent/$', signup_views.account_activation_sent, name='account_activation_sent'),
url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', signup_views.activate, name='activate'),

似乎出现错误是因为您的令牌有 32 个字符,但正则表达式最多只需要 20 个字符。尝试将正则表达式更改为:

r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,32})/$'
                                                                   # Change to 32 ^^