User registration in Django

One of the projects I just finished was once again, written and deployed using Django, and even after 1.5 years of using this baby, I'm still stoked by how flexible and powerful it is. The project consisted of a CMS that had to power 4 different sites, so it was a crazy 3 months and I'm still amazed I managed to pull it off with the help of 2 friends (Kim, Peiling) and lots of coffee.

One of the things that hit me at 5am before the launch day was that I needed to create and enable user registration for the 4 sites, and thankfully, they wanted to have only one single login for the users. One of the things that Django doesn't really have with its built in user registration stuff is the ability to send out account activation emails. To get around that, I (again this is 5am with a konked out brain) decided to work on it as simply as I can. Here's how:

Extend the User with a Profile model

I have a field here to basically store the token and status of the user accounts. So before I log anyone in, an extra check after a initial one via the User model with the status field allows me to show a message to remind a user that they need to activate their account first.

Assign a token during registration

I'll like to be as random and long as possible, and an example of generating a token (there're tons of ways of course) would be like,

This is then assigned to the Profile instance during registration and the status is by default set to false. After the save method on the model is called, I've another model method called 'send_token_mail' that simply fills in a email template and sends the rendered link to the user's email address (provided in the registration form)

This can be done easily with Django's built in send_mail function. The final step was to hook up a receiving end in my urlconf and I'm set to go.

is a good skeleton of the receiving end's view function.

Thoughts

There's some good libraries out there for handling this better, and django-registration is one such example. I didn't use it for other reasons, but it could be a better setup for you instead. See this post for a good tutorial.