[Solved]-Send email confirmation after registration django

17👍

Django provides a token creation mechanism, there is no need to reinvent the wheel.
Since I don’t use function based views and the point here is not to refactor your code (I would do it in CBVs anyway), I will just output a sample on how you can use it.

from django.contrib.auth.tokens import default_token_generator
from django.utils.http import urlsafe_base64_encode
from django.utils.encoding import force_bytes

new_user = User.objects.create_user(username=usuario,
                                    email=email,
                                    password=clave)
new_user.save()
token = default_token_generator.make_token(new_user)
uid = urlsafe_base64_encode(force_bytes(new_user.pk))

You can then email the token to the user, the token url should look like:

url(r'^users/validate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
    activationview,
    name='user-activation-link')

Somewhere in your activationview:

from django import http

uidb64 = request.GET.get('uidb64')
token = request.GET.get('token')

if uidb64 is not None and token is not None:
    from django.utils.http import urlsafe_base64_decode
    uid = urlsafe_base64_decode(uidb64)
    try:
        from django.contrib.auth import get_user_model
        from django.contrib.auth.tokens import default_token_generator
        user_model = get_user_model()
        user = user_model.objects.get(pk=uid)
        if default_token_generator.check_token(user, token) and user.is_active == 0:
            # Do success stuff...
            return http.HttpResponseRedirect(a_success_url)
    except:
        pass

return http.HttpResponseRedirect(a_failure_url)

Leave a comment