Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

python - Email activation link issue in Django 3.1.3

Well, I decided to implement an account authentication system by sending an activation link to the email of the user who just registered and here are the views and the message sent

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(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(
                'users/email_template.html',
                {
                    'user': user,
                    'domain': current_site.domain,
                    'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                    'token': account_activation_token.make_token(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:
        form = UserRegisterForm()
    return render(request, 'users/register.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.save()
        login(request, user)
        return HttpResponse('Thank you for your email confirmation. Now you can login account.')
     else:
        return HttpResponse('Activation link is invalid!')

Token Generator class:

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


 class TokenGenerator(PasswordResetTokenGenerator):
       def _make_hash_value(self, user, timestamp):
           return (
               text_type(user.pk) + text_type(timestamp) +
               text_type(user.is_active)
           )

 account_activation_token = TokenGenerator()

The template with the message:

 {% autoescape off %}
     Hi {{ user.username }},
     Please click on the link to confirm your registration

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

url.py:

urlpatterns = [
    path('register/', views.register, name='register'),
    path('activate/<uidb64>/<token>/', views.activate, name='activate'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path("profile/<str:username>/", views.profile, name="profile"),
]

Everything is working fine, but there is a problem with the activation link, it appears like this: http://localhost:8000//users/activate/MTY/agxxit-58f6e97c157ac2855dd80794f2ce9c62/ with two bars after port 8000, which is generate an error, to work I need to edit the link in the browser bar, removing one of the bars. Does anyone know how to organize this link so that it does not appear with the two bars after port 8000?

question from:https://stackoverflow.com/questions/65863640/email-activation-link-issue-in-django-3-1-3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your domain name must be "www.example.com" without any slashes.

From Django: domain - The fully qualified domain name associated with the website. For example, www.example.com.

So change site domain via /admin/sites/site/

In your case it should be: localhost:8000


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...