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