Jake 1986
Jake 1986

Reputation: 602

Django - how to get email links to work on mobile?

My Django site sends out an email confirmation link, and everything seems to work fine on desktop. On mobile devices, however, the link text is highlighted blue and underlined (i.e. it looks like a link) but nothing happens when the user clicks it. It should open a browser tab and say, "you have confirmed your email, etc"

Thanks for any tips!

views.py:

def signup(request):
    if request.method == 'POST':
        #send signup form
        email_address = request.POST['email']
        if request.POST['password1'] == request.POST['password2']:
            try:
                user = User.objects.get(email=email_address)
                return render(request, 'accounts/signup.html', {'error': "Email already in use."})
            except User.DoesNotExist:
                user = User.objects.create_user(request.POST['email'], password=request.POST['password1'])
                #auth.login(request, user)
                #send email confirmation link then redirect:
                #user = User.objects.get(email=email_address)
                current_site = get_current_site(request)
                mail_subject = 'Welcome to My Site'
                plain_msg = 'Thank you for signing up to My Site! Click this link to activate your account:\n\n'+current_site.domain+'/accounts/activated/'+urlsafe_base64_encode(force_bytes(user.pk)).decode()+'/'+account_activation_token.make_token(user)+'/'
                msg = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>title</title></head><body>Confirm your email address to continue:<br/><a href="'+current_site.domain+'/accounts/activated/'+urlsafe_base64_encode(force_bytes(user.pk)).decode()+'/'+account_activation_token.make_token(user)+'/">Confirm my email address</a></body></html>'
                print(msg)
                send_mail(mail_subject, plain_msg, '[email protected]', [email_address], html_message=msg)
                return render(request, 'accounts/activation-link-sent.html', {'email': email_address})
    #truncated for Stack Overflow post

Upvotes: 0

Views: 293

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32284

You should use build_absolute_uri to create fully qualified links that include the current domain and protocol, then use this link in your email

link = request.build_absolute_uri('/accounts/activated/'+urlsafe_base64_encode(force_bytes(user.pk)).decode()+'/'+account_activation_token.make_token(user)+'/')

Do you have a url pattern that matches this URL? You should consider using reverse for building URLs

path = reverse('activate', kwargs={
    'pk': user.pk,
    'token': account_activation_token.make_token(user)
})
link = request.build_absolute_uri(path)

Upvotes: 1

Related Questions