How to Create User Sign Up View. Feb 18, 2017 17 minutes read. From django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth. From django.contrib.auth import login from django.contrib.auth.models import User from django.shortcuts import render, redirect from django.utils.encoding import force.
Posted byLast updated on February 7th, 2019How do I fully replace the username field with an email field for Django authentication?This post explains step-by-step how to create a custom in Django so that an email address can be used as the primary user identifier instead of a username for authentication.Keep in mind that the process outlined in this post requires significant changes to the database schema. Because of this, it's only recommended for new projects. If this is for an existing legacy project, you'll probably have to back up the data and recreate the database. For more on this, review the following resources:. guide from the official Django docs. blog postContents.AbstractUser vs AbstractBaseUserThe default User model in Django uses a username to uniquely identify a user during authentication.
From django.test import TestCase from django.contrib.auth import getusermodel class UsersManagersTests ( TestCase ): def testcreateuser ( self ): User = getusermodel user = User. Createuser ( email = ', password = 'foo' ) self. AssertEqual ( user. Email, ' ) self.
AssertTrue ( user. Isactive ) self.
AssertFalse ( user. Isstaff ) self. AssertFalse ( user. Issuperuser ) try: # username is None for the AbstractUser option # username does not exist for the AbstractBaseUser option self. AssertIsNone ( user. Username ) except AttributeError: pass with self. AssertRaises ( TypeError ): User.
Createuser with self. AssertRaises ( TypeError ): User. Createuser ( email = ' ) with self. AssertRaises ( ValueError ): User. Createuser ( email = ', password = 'foo' ) def testcreatesuperuser ( self ): User = getusermodel adminuser = User. Createsuperuser ( ', 'foo' ) self. AssertEqual ( adminuser.
Email, ' ) self. AssertTrue ( adminuser. Isactive ) self. AssertTrue ( adminuser. Isstaff ) self. AssertTrue ( adminuser.
Issuperuser ) try: # username is None for the AbstractUser option # username does not exist for the AbstractBaseUser option self. AssertIsNone ( adminuser. Username ) except AttributeError: pass with self. AssertRaises ( ValueError ): User. Createsuperuser ( email = ', password = 'foo', issuperuser = False )Add the specs to users/tests.py, and then make sure the tests fail.
Model ManagerFirst, we need to add a custom, by subclassing BaseUserManager, that uses an email as the unique identifier instead of a username.Create a managers.py file in the 'users' directory. From django.contrib.auth.baseuser import BaseUserManager from django.utils.translation import ugettextlazy as class CustomUserManager ( BaseUserManager ): ' Custom user model manager where email is the unique identifiers for authentication instead of usernames. ' def createuser ( self, email, password,. extrafields ): ' Create and save a User with the given email and password. ' if not email: raise ValueError ( ( 'The Email must be set' )) email = self. Normalizeemail ( email ) user = self.
Model ( email = email,. extrafields ) user. Setpassword ( password ) user. Save return user def createsuperuser ( self, email, password,. extrafields ): ' Create and save a SuperUser with the given email and password. ' extrafields. Setdefault ( 'isstaff', True ) extrafields.
Setdefault ( 'issuperuser', True ) extrafields. Setdefault ( 'isactive', True ) if extrafields. Get ( 'isstaff' ) is not True: raise ValueError ( ( 'Superuser must have isstaff=True.' )) if extrafields. Get ( 'issuperuser' ) is not True: raise ValueError ( ( 'Superuser must have issuperuser=True.'
)) return self. Createuser ( email, password,. extrafields ) User ModelDecide which option you'd like to use-subclassing AbstractUser or AbstractBaseUser. AbstractUserUpdate users/models.py. From django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettextlazy as from.managers import CustomUserManager class CustomUser ( AbstractUser ): username = None email = models.
EmailField ( ( 'email address' ), unique = True ) USERNAMEFIELD = 'email' REQUIREDFIELDS = objects = CustomUserManager def str ( self ): return self. EmailHere, we:. Created a new class called CustomUser that subclasses AbstractUser. Removed the username field.
Made the email field required and unique. Set the USERNAMEFIELD-which defines the unique identifier for the User model-to email. Specified that all objects for the class come from the CustomUserManagerAbstractBaseUserUpdate users/models.py. From django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import gettextlazy as from django.utils import timezone from.managers import CustomUserManager class CustomUser ( AbstractBaseUser, PermissionsMixin ): email = models. EmailField ( ( 'email address' ), unique = True ) isstaff = models. BooleanField ( default = False ) isactive = models. BooleanField ( default = True ) datejoined = models.
DateTimeField ( default = timezone. Now ) USERNAMEFIELD = 'email' REQUIREDFIELDS = objects = CustomUserManager def str ( self ): return self. EmailHere, we:. Created a new class called CustomUser that subclasses AbstractBaseUser. Added fields for email, isstaff, isactive, and datejoined.
Set the USERNAMEFIELD-which defines the unique identifier for the User model-to email. Specified that all objects for the class come from the CustomUserManagerSettingsAdd the following line to the settings.py file so that Django knows to use the new User class.
In this tutorial we’ll learn how to configure login/logout functionality in Django 2.1 with the built-in. Future tutorials cover as well as a. By the end of these tutorials you’ll have a complete user authentication flow for your future Django projects.This tutorial assumes you’re already familiar with how to configure a new Django project.
If you need help, please refer to which covers the topic in more detail.Note if you’re looking for information on or, I have separate tutorials on those, too. And when you’re ready to put it all together check out my which shows how to combine a custom user model with social login with Gmail.Complete source code can be found. SetupStart by creating a new Django project.
This code can live anywhere on your computer. On a Mac, the desktop is a convenient place and that’s where we’ll put this code.
We can do all of the normal configuration from the command line:. create a new accounts directory for our code on the Desktop. install Django with Pipenv. start the virtual environment shell. create a new Django project called myproject.
create a new Sqlite database with migrate. run the local serverHere are the commands to run.
$ cd /Desktop$ mkdir accounts && cd accounts$ pipenv install django2.1$ pipenv shell(accounts) $ django-admin.py startproject myproject.(accounts) $ python manage.py migrate(accounts) $ python manage.py runserverIf you navigate to you’ll see the Django welcome screen.The Django auth appDjango automatically installs the auth app when a new project is created. Look in the settings.py under INSTALLEDAPPS and you can see auth is one of several built-in apps Django has installed for us. Accounts/login/ name='login'accounts/logout/ name='logout'accounts/passwordchange/ name='passwordchange'accounts/passwordchange/done/ name='passwordchangedone'accounts/passwordreset/ name='passwordreset'accounts/passwordreset/done/ name='passwordresetdone'accounts/reset/// name='passwordresetconfirm'accounts/reset/done/ name='passwordresetcomplete'There are associated auth views for each URL pattern, too. That means we only need to create a template to use each!
Login PageLet’s make our login page! Django by default will look within a templates folder called registration for auth templates. The login template is called login.html.Create a new directory called registration and the requisite login.html file within it. From the command line type Control-c to quit our local server and enter the following commands. # myproject/settings.py LOGINREDIRECTURL = '/'We’re actually done at this point!If you now start up the Django server again with python manage.py runserver and navigate to our login page at you’ll see the following.Create usersBut there’s one missing piece: we haven’t created any users yet. Let’s quickly do that by making a superuser account from the command line.
Quit the server with Control+c and then run the command python manage.py createsuperuser. Answer the prompts and note that your password will not appear on the screen when typing for security reasons. (accounts) $ python manage.py createsuperuserUsername (leave blank to use 'wsv'):Email address: [email protected]:Password (again):Superuser created successfully.Now spin up the server again with python manage.py runserver and refresh the page at.
Enter the login info for your just-created user.We know that our login worked because we were redirected to the homepage, but we haven’t created it yet so we see the error Page not found. Let’s fix that! Create a homepageWe want a simple homepage that will display one message to logged out users and another to logged in users.First quit the local server with Control+c and then create new base.html and home.html files. Note that these are located within the templates folder but not within templates/registration/ where Django auth looks by default for user auth templates. # myproject/urls.py from django.contrib import admin from django.urls import path, include from django.views.generic.base import TemplateView # new urlpatterns = path ( 'admin/', admin. Urls ), path ( 'accounts/', include ( 'django.contrib.auth.urls' )), path ( ', TemplateView.
Asview ( templatename = 'home.html' ), name = 'home' ), # new And we’re done. If you start the Django server again with python manage.py runserver and navigate to the homepage at you’ll see the following:It worked!
But how do we logout? The only option currently is to go into the admin panel at and click on the “Logout” link in the upper right corner.This will log us out as seen by the redirect page:If you go to the homepage again at and refresh the page, we can see we’re logged out.Logout linkLet’s add a logout link to our page so users can easily toggle back and forth between the two states. Fortunately the Django auth app already provides us with a built-in url and view for this. And if you think about it, we don’t need to display anything on logout so there’s no need for a template. All really we do after a successful “logout” request is redirect to another page.So let’s first add a link to the built-in logout url in our home.html file. # myproject/settings.py LOGINREDIRECTURL = 'home' LOGOUTREDIRECTURL = 'home'Now if you revisit the homepage and login you’ll be redirected to the new hompage that has a “logout” link for logged in users.Clicking it takes you back to the homepage with a “login” link.ConclusionWith very little code we have a robust login and logout authentication system. It probably feels a bit like magic since the auth app did much of the heavy lifting for us.
One of the nice things about Django is while it provides a lot of functionality out-of-the-box, it’s designed to be customizable too.In the next post, we’ll learn how to add a signup page to register new users.