Django offers almost the entire user management logic of a typical website out of the box. User login, logout, change password, reset the password, all of these are ready as soon as you start a new project.
But I said "almost" because there's one thing that's needed almost in every website that's not offered in Django: email verification. Fear not though. The functionality might not be offered out-of-the-box but all the required components are there.
The most crucial bit for the email verification flow is the verification token. The purpose of this token is to encode the user's current state. We want it to be valid only if the user is inactive. When the user is activated, the token should no longer be valid.
Thankfully, Django creates similar tokens when sending password reset emails. We can reuse that class to create the tokens for the email activation as well.
The only difference is what elements we use to generate the token. Since we want the tokens to be valid only when the user is not yet activated, we will include
The next step is to send the verification email.
Note that we need 3 things to construct the activation URL:
- The current domain
- The user id, which we are encoding using Base64
- The token we discussed in the previous section
Activate the user
The last step is to activate the user. We do the reverse process we did in the previous step.
- Base64 decode to get the user id
- Fetching the user using the user id
- Using the
EmailVerificationTokenGeneratorto verify that the token is still valid
If the token is valid, which means the user is not yet activated, we set the
True and save. From this point on, the token will not be valid anymore. So we need to handle the case where this link is clicked again to display the appropriate message in the template.
Hopefully, this was a quick and straightforward way to implement email verification in your Django project.