django User registration and authentication by email

eagertoLearn picture eagertoLearn · Mar 14, 2014 · Viewed 10.6k times · Source

I want to make users active by sending them an activation email to click. I guess it is currently not incorporated in Django 1.6.The user-registration app coded in Django seems to serve this purpose. But I have some doubts with regard to the DefaultForm it provides in forms.py. I want to have more fields included in it. How can I achieve that in class RegistrationForm(forms.Form) implemented there. If I install this app, is it a good idea to change include more fields directly there, is there a better way to achieve the same.

In the views.py, I see some methods such as the following are not implemented. I dont have a clear picture of what these methods need to do. should I redirect the url here to the pages?

def register(self, request, **cleaned_data):
 raise NotImplementedError

def activate(self, request, *args, **kwargs):

        raise NotImplementedError

    def get_success_url(self, request, user):
        raise NotImplementedError

Answer

Aaron Lelevier picture Aaron Lelevier · Mar 14, 2014

You need to first let them sign up and mark them as is_active=False for the time being. Something like this:

from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.http import HttpResponseRedirect

def signup(request):
  # form to sign up is valid
  user = User.objects.create_user('username', 'email', 'password')
  user.is_active=False
  user.save()

  # now send them an email with a link in order to activate their user account
  #   you can also use an html django email template to send the email instead
  #   if you want
  send_mail('subject', 'msg [include activation link to View here to activate account]', 'from_email', ['to_email'], fail_silently=False)

 return HttpResponseRedirect('register_success_view')

Then once they click the link in the email it takes them to the next view (note: you need to put a link in the email so that you know which user it is. This may be 16-digit salt or something. The below view uses the user.pk:

def activate_view(request, pk):
  user = User.objects.get(pk=pk)
  user.is_active=True
  user.save()
  return HttpResponseRedirect('activation_success_view')

Hope that helps. Good Luck!