Django delete superuser - python

This may be a duplicate, but I couldn't find the question anywhere, so I'll go ahead and ask:
Is there a simple way to delete a superuser from the terminal, perhaps analogous to Django's createsuperuser command?

There's no built in command but you can easily do this from the shell:
> python manage.py shell
$ from django.contrib.auth.models import User
$ User.objects.get(username="joebloggs", is_superuser=True).delete()

In the case of a custom user model it would be:
python manage.py shell
from django.contrib.auth import get_user_model
model = get_user_model()
model.objects.get(username="superjoe", is_superuser=True).delete()

An answer for people who did not use Django's User model instead substituted a Django custom user model.
class ManagerialUser(BaseUserManager):
""" This is a manager to perform duties such as CRUD(Create, Read,
Update, Delete) """
def create_user(self, email, name, password=None):
""" This creates a admin user object """
if not email:
raise ValueError("It is mandatory to require an email!")
if not name:
raise ValueError("Please provide a name:")
email = self.normalize_email(email=email)
user = self.model(email=email, name=name)
""" This will allow us to store our password in our database
as a hash """
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, name, password):
""" This creates a superuser for our Django admin interface"""
user = self.create_user(email, name, password)
user.is_superuser = True
user.is_staff = True
user.save(using=self._db)
return user
class TheUserProfile(AbstractBaseUser, PermissionsMixin):
""" This represents a admin User in the system and gives specific permissions
to this class. This class wont have staff permissions """
# We do not want any email to be the same in the database.
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name',]
# CLASS POINTER FOR CLASS MANAGER
objects = ManagerialUser()
def get_full_name(self):
""" This function returns a users full name """
return self.name
def get_short_name(self):
""" This will return a short name or nickname of the admin user
in the system. """
return self.name
def __str__(self):
""" A dunder string method so we can see a email and or
name in the database """
return self.name + ' ' + self.email
Now to delete a registered SUPERUSER in our system:
python3 manage.py shell
>>>(InteractiveConsole)
>>>from yourapp.models import TheUserProfile
>>>TheUserProfile.objects.all(email="The email you are looking for", is_superuser=True).delete()

No need to delete superuser...just create another superuser... You can create another superuser with same name as the previous one.
I have forgotten the password of the superuser so I create another superuser with the same name as previously.

Here's a simple custom management command, to add in myapp/management/commands/deletesuperuser.py:
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.core.management.base import CommandError
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('username', type=str)
def handle(self, *args, **options):
try:
user = User.objects.get(username=options['username'], is_superuser=True)
except User.DoesNotExist:
raise CommandError("There is no superuser named {}".format(options['username']))
self.stdout.write("-------------------")
self.stdout.write("Deleting superuser {}".format(options.get('username')))
user.delete()
self.stdout.write("Done.")
https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/#accepting-optional-arguments

A variation from #Timmy O'Mahony answer is to use the shell_plus (from django_extensions) to identify your User model automatically.
python manage.py shell_plus
User.objects.get(
username="joebloggs",
is_superuser=True
).delete()
If the user email is unique, you can delete the user by email too.
User.objects.get(
email="joebloggs#email.com",
is_superuser=True
).delete()

There is no way to delete it from the Terminal (unfortunately), but you can delete it directly. Just log into the admin page, click on the user you want to delete, scroll down to the bottom and press delete.

Related

Django log login attemps and after 3 failed attemps lock out user

So i am pretty new to Django. Actually my first project.
I want to create a custom model "Logging" in which i want to log the admin login attempts and count the attempts. After 3 failed login attempts the user must me locked out. Ive already created a custom User model like this.
class UserManager(BaseUserManager):
def create_user(self,username,password,description):
if not username:
raise ValueError('Users must have an username ')
user = self.model(username=username)
user.set_password(password)
user.description = description
user.save(using=self._db)
return user
def create_staffuser(self, username, password, description):
user = self.create_user(
username,
password,
description
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, username, password, description):
user = self.model(username=username)
user.set_password(password)
user.description = description
user.staff = True
user.admin = True
user.save(using=self._db)
return user
class Users(AbstractBaseUser):
username = models.CharField(max_length=15,unique=True)
description = models.CharField(max_length=50,default="None")
is_active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
# notice the absence of a "Password field", that is built in.
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['description']
def get_full_name(self):
return self.username
def get_short_name(self):
return self.username
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
#property
def is_staff(self):
"Is the user a member of staff?"
return self.staff
#property
def is_admin(self):
"Is the user a admin member?"
return self.admin
objects = UserManager()
So how can i log custom admin attempts?
You can make signal receivers for the user_login_failed [Django-doc] and user_logged_in [Django-doc] signals. We can thus create a model that looks like:
from django.conf import settings
class FailedLogin(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
timestamp = models.DateTimeField(auto_now_add=True)
Then we define two signal receivers, one for a successful login that will remove FailedLogin records (if any):
from django.contrib.auth import get_user_model
from django.contrib.auth.signals import user_logged_in, user_login_failed
from django.dispatch import receiver
#receiver(user_logged_in)
def user_logged_recv(sender, request, user, **kwargs):
FailedLogin.objects.filter(user=user).delete()
#receiver(user_login_failed)
def user_login_failed_recv(sender, credentials, request):
User = get_user_model()
try:
u = User.objects.get(username=credentials.get('username'))
# there is a user with the given username
FailedLogin.objects.create(user=u)
if FailedLogin.objects.filter(user=u).count() >= 3:
# three tries or more, disactivate the user
u.is_active = False
u.save()
except User.DoesNotExist:
# user not found, we can not do anything
pass

Group and Permissions Assignment Missing when using Custom User Model

I am building an app with multiple roles defined through Django Groups.
I started with a custom user model, defined as below.
I am seeing a weird difference in the groups and permissions use when using a custom user model, like the inheritance is missing something.
I would like to use a custom user model so I don't use username but I also need multiple groups and permissions in my application.
from django.db import models
from django.contrib.auth.models import AbstractUser, AbstractBaseUser, BaseUserManager, PermissionsMixin
import random
import string
from slugify import slugify
# Create your models here.
class MyAccountManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError("You must have an email address")
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(
email=self.normalize_email(email),
)
user.set_password(password)
user.is_admin=True
user.is_staff=True
user.is_superuser=True
user.save(using=self._db)
return user
#custom user account model
class User_Account(AbstractUser):
email = models.EmailField(verbose_name='email', max_length=60, unique = True)
date_joined = models.DateTimeField(verbose_name="Date Joined", auto_now_add=True)
last_login = models.DateTimeField(verbose_name="Last Login", auto_now=True)
username = models.CharField(max_length=100, null=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = MyAccountManager()
def __str__(self):
return self.email
When I create a new group with the custom user model, the group gets automatically assigned to all created users. I reproduced this behavior both programmatically and through the Django Admin.
When I use the default user model the group creation doesn't assign groups to all users automatically.
I also discovered that when using a custom user model the Django Admin for the users is not the same (the group and permission assignment fields are incomplete - screenshots below)
Weird incomplete Django Admin interface with groups and permissions missing the available fields
Normal Django Admin interface with group and permission assignment as expected - default user model
I managed to fix the issue in the Admin panel. It seems that it's a visual rendering problem caused by a wrong Admin class.
The error was caused by the following:
filter_horizontal = ()
list_filter = ()
fieldsets = ()
I have actually added the proper parameters in the class above but forgot to comment out/remove these lines. Works properly after commenting them out.
Try removing
filter_horizontal = (),
It worked for me.

Creating a custom super user as part of a class Im taking

I'm currently taking a custom rest API class that is teaching me to build my own custom REST APIs for authentication, as well as creating custom user models.
Im running into a slight problem with the following code base:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager
# Create your models here.
class UserProfileManager(BaseUserManager):
""" Manager for User Profiles"""
def create_user(self, email, name, password=None):
""" Create a new user profile"""
if not email:
raise ValueError('Users must have an email address')
email = self.normalize_email(email)
user = self.model(email=email, name=name)
""" user.set_password(password) encrypts the passwords as a hash """
user.set_password(password)
""" This allows you to specify which database to use for the user accounts. Django Supports multiple Databases!!! 8D """
user.save(using=self._db)
return user
def create_superusr(self, email, name, password):
""" Create and save a new superuser with given details """
user = self.create_user(email, name, password)
user.is_superuser = True
user.is_staff = True
user.save(using=self._db)
return user
class UserProfile(AbstractBaseUser, PermissionsMixin):
""" Database model for users in system """
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserProfileManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
def get_full_name(self):
""" Retrieve Full Name of User"""
return self.name
def get_short_name(self):
""" Retrieve short name of User"""
return self.name
def __str__(self):
"""Return String representation of our User """
return self.email
The primary issue is in the UserProfileManager section, the issue according to the error output is with the create_superuser section.
The error message is the following:
AttributeError: 'UserProfileManager' object has no attribute 'create_superuser'
I've checked to ensure that in my settings.py file to ensure that using the custom model, as well as Ive checked to confirm that the makemigrations and migrations commands have been run. Ive also tested by deleting the init files, as well as the database and rebuilding them.
Ive also tested to ensure that superuser works, and django admin portal is enabled, all of which without the custom user profile works fine, but with it it breaks, so I know my issue should have something to do with the section of code above, but I cant find anything. Ive checked with the official django docs, but Im at a loss at this point.
I found my error. E for Error, as in the e that was missing in def create_superusEr.
Im good now! This site is awesome! Sometimes just asking the question helps to answer it.

Django - Login with Email

I want django to authenticate users via email, not via usernames. One way can be providing email value as username value, but I dont want that. Reason being, I've a url /profile/<username>/, hence I cannot have a url /profile/abcd#gmail.com/.
Another reason being that all emails are unique, but it happen sometimes that the username is already being taken. Hence I'm auto-creating the username as fullName_ID.
How can I just change let Django authenticate with email?
This is how I create a user.
username = `abcd28`
user_email = `abcd#gmail.com`
user = User.objects.create_user(username, user_email, user_pass)
This is how I login.
email = request.POST['email']
password = request.POST['password']
username = User.objects.get(email=email.lower()).username
user = authenticate(username=username, password=password)
login(request, user)
Is there any other of of login apart from getting the username first?
You should write a custom authentication backend. Something like this will work:
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class EmailBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
UserModel = get_user_model()
try:
user = UserModel.objects.get(email=username)
except UserModel.DoesNotExist:
return None
else:
if user.check_password(password):
return user
return None
Then, set that backend as your auth backend in your settings:
AUTHENTICATION_BACKENDS = ['path.to.auth.module.EmailBackend']
Updated. Inherit from ModelBackend as it implements methods like get_user() already.
See docs here: https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#writing-an-authentication-backend
If you’re starting a new project, django highly recommended you to set up a custom user model. (see https://docs.djangoproject.com/en/dev/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project)
and if you did it, add three lines to your user model:
class MyUser(AbstractUser):
USERNAME_FIELD = 'email'
email = models.EmailField(_('email address'), unique=True) # changes email to unique and blank to false
REQUIRED_FIELDS = [] # removes email from REQUIRED_FIELDS
Then authenticate(email=email, password=password) works, while authenticate(username=username, password=password) stops working.
Email authentication for Django 3.x
For using email/username and password for authentication instead of the default username and password authentication, we need to override two methods of ModelBackend class: authenticate() and get_user():
The get_user method takes a user_id – which could be a username, database ID or whatever, but has to be unique to your user object – and returns a user object or None. If you have not kept email as a unique key, you will have to take care of multiple result returned for the query_set. In the below code, this has been taken care of by returning the first user from the returned list.
from django.contrib.auth.backends import ModelBackend, UserModel
from django.db.models import Q
class EmailBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
try: #to allow authentication through phone number or any other field, modify the below statement
user = UserModel.objects.get(Q(username__iexact=username) | Q(email__iexact=username))
except UserModel.DoesNotExist:
UserModel().set_password(password)
except MultipleObjectsReturned:
return User.objects.filter(email=username).order_by('id').first()
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user
def get_user(self, user_id):
try:
user = UserModel.objects.get(pk=user_id)
except UserModel.DoesNotExist:
return None
return user if self.user_can_authenticate(user) else None
By default, AUTHENTICATION_BACKENDS is set to:
['django.contrib.auth.backends.ModelBackend']
In settings.py file, add following at the bottom to override the default:
AUTHENTICATION_BACKENDS = ('appname.filename.EmailBackend',)
Django 4.0
There are two main ways you can implement email authentication, taking note of the following:
emails should not be unique on a user model to mitigate misspellings and malicious use.
emails should only be used for authentication if they are verified (as in we have sent a verification email and they have clicked the verify link).
We should only send emails to verified email addresses.
Custom User Model
A custom user model is recommended when starting a new project as changing mid project can be tricky.
We will add an email_verified field to restrict email authentication to users with a verified email address.
# app.models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
email_verified = models.BooleanField(default=False)
We will then create a custom authentication backend that will substitute a given email address for a username.
This backend will work with authentication forms that explicitly set an email field as well as those setting a username field.
# app.backends.py
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
UserModel = get_user_model()
class CustomUserModelBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD, kwargs.get(UserModel.EMAIL_FIELD))
if username is None or password is None:
return
try:
user = UserModel._default_manager.get(
Q(username__exact=username) | (Q(email__iexact=username) & Q(email_verified=True))
)
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a nonexistent user (#20760).
UserModel().set_password(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user
We then modify our projects settings.py to use our custom user model and authentication backend.
# project.settings.py
AUTH_USER_MODEL = "app.User"
AUTHENTICATION_BACKENDS = ["app.backends.CustomUserModelBackend"]
Be sure that you run manage.py makemigrations before you migrate and that the first migration contains these settings.
Extended User Model
While less performant than a custom User model (requires a secondary query), it may be better to extend the existing User model in an existing project and may be preferred depending on login flow and verification process.
We create a one-to-one relation from EmailVerification to whichever User model our project is using through the AUTH_USER_MODEL setting.
# app.models.py
from django.conf import settings
from django.db import models
class EmailVerification(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_query_name="verification"
)
verified = models.BooleanField(default=False)
We can also create a custom admin that includes our extension inline.
# app.admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import EmailVerification
UserModel = get_user_model()
class VerificationInline(admin.StackedInline):
model = EmailVerification
can_delete = False
verbose_name_plural = 'verification'
class UserAdmin(BaseUserAdmin):
inlines = (VerificationInline,)
admin.site.unregister(UserModel)
admin.site.register(UserModel, UserAdmin)
We then create a backend similar to the one above that simply checks the related models verified field.
# app.backends.py
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
UserModel = get_user_model()
class ExtendedUserModelBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD, kwargs.get(UserModel.EMAIL_FIELD))
if username is None or password is None:
return
try:
user = UserModel._default_manager.get(
Q(username__exact=username) | (Q(email__iexact=username) & Q(verification__verified=True))
)
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a nonexistent user (#20760).
UserModel().set_password(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user
We then modify our projects settings.py to use our authentication backend.
# project.settings.py
AUTHENTICATION_BACKENDS = ["app.backends.ExtendedUserModelBackend"]
You can then makemigrations and migrate to add functionality to an existing project.
Notes
if usernames are case insensitive change Q(username__exact=username) to Q(username__iexact=username).
In production prevent a new user registering with an existing verified email address.
I had a similar requirement where either username/email should work for the username field.In case someone is looking for the authentication backend way of doing this,check out the following working code.You can change the queryset if you desire only the email.
from django.contrib.auth import get_user_model # gets the user_model django default or your own custom
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
# Class to permit the athentication using email or username
class CustomBackend(ModelBackend): # requires to define two functions authenticate and get_user
def authenticate(self, username=None, password=None, **kwargs):
UserModel = get_user_model()
try:
# below line gives query set,you can change the queryset as per your requirement
user = UserModel.objects.filter(
Q(username__iexact=username) |
Q(email__iexact=username)
).distinct()
except UserModel.DoesNotExist:
return None
if user.exists():
''' get the user object from the underlying query set,
there will only be one object since username and email
should be unique fields in your models.'''
user_obj = user.first()
if user_obj.check_password(password):
return user_obj
return None
else:
return None
def get_user(self, user_id):
UserModel = get_user_model()
try:
return UserModel.objects.get(pk=user_id)
except UserModel.DoesNotExist:
return None
Also add AUTHENTICATION_BACKENDS = ( 'path.to.CustomBackend', ) in settings.py
Email and Username Authentication for Django 2.X
Having in mind that this is a common question, here's a custom implementation mimicking the Django source code but that authenticates the user with either username or email, case-insensitively, keeping the timing attack protection and not authenticating inactive users.
from django.contrib.auth.backends import ModelBackend, UserModel
from django.db.models import Q
class CustomBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
try:
user = UserModel.objects.get(Q(username__iexact=username) | Q(email__iexact=username))
except UserModel.DoesNotExist:
UserModel().set_password(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user
def get_user(self, user_id):
try:
user = UserModel.objects.get(pk=user_id)
except UserModel.DoesNotExist:
return None
return user if self.user_can_authenticate(user) else None
Always remember to add it your settings.py the correct Authentication Backend.
It seems that the method of doing this has been updated with Django 3.0.
A working method for me has been:
authentication.py # <-- I placed this in an app (did not work in the project folder alongside settings.py
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import BaseBackend
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User
class EmailBackend(BaseBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
UserModel = get_user_model()
try:
user = UserModel.objects.get(email=username)
except UserModel.DoesNotExist:
return None
else:
if user.check_password(password):
return user
return None
def get_user(self, user_id):
UserModel = get_user_model()
try:
return UserModel.objects.get(pk=user_id)
except UserModel.DoesNotExist:
return None
Then added this to the settings.py file
AUTHENTICATION_BACKENDS = (
'appname.authentication.EmailBackend',
)
I have created a helper for that: function authenticate_user(email, password).
from django.contrib.auth.models import User
def authenticate_user(email, password):
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
return None
else:
if user.check_password(password):
return user
return None
class LoginView(View):
template_name = 'myapp/login.html'
def get(self, request):
return render(request, self.template_name)
def post(self, request):
email = request.POST['email']
password = request.POST['password']
user = authenticate_user(email, password)
context = {}
if user is not None:
if user.is_active:
login(request, user)
return redirect(self.request.GET.get('next', '/'))
else:
context['error_message'] = "user is not active"
else:
context['error_message'] = "email or password not correct"
return render(request, self.template_name, context)
Authentication with Email and Username For Django 2.x
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
class EmailorUsernameModelBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
UserModel = get_user_model()
try:
user = UserModel.objects.get(Q(username__iexact=username) | Q(email__iexact=username))
except UserModel.DoesNotExist:
return None
else:
if user.check_password(password):
return user
return None
In settings.py, add following line,
AUTHENTICATION_BACKENDS = ['appname.filename.EmailorUsernameModelBackend']
You should customize ModelBackend class.
My simple code:
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
class YourBackend(ModelBackend):
def authenticate(self, username=None, password=None, **kwargs):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
if '#' in username:
UserModel.USERNAME_FIELD = 'email'
else:
UserModel.USERNAME_FIELD = 'username'
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
UserModel().set_password(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user
And in settings.py file, add:
AUTHENTICATION_BACKENDS = ['path.to.class.YourBackend']
from django.contrib.auth.models import User
from django.db import Q
class EmailAuthenticate(object):
def authenticate(self, username=None, password=None, **kwargs):
try:
user = User.objects.get(Q(email=username) | Q(username=username))
except User.DoesNotExist:
return None
except MultipleObjectsReturned:
return User.objects.filter(email=username).order_by('id').first()
if user.check_password(password):
return user
return None
def get_user(self,user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
And then in settings.py:
AUTHENTICATION_BACKENDS = (
'articles.backends.EmailAuthenticate',
)
where articles is my django-app, backends.py is the python file inside my app and EmailAuthenticate is the authentication backend class inside my backends.py file
May, 2022 Update:
This instruction shows how to set up authentication with "email" and "password" instead of "username" and "password" and in this instruction, "username" is removed and I tried not to change the default Django settings as much as possible.
First, run the command below to create "account" application:
python manage.py startapp account
Then, set "account" application to "INSTALLED_APPS" and set AUTH_USER_MODEL = 'account.CustomUser' in "settings.py" as shown below:
# "settings.py"
INSTALLED_APPS = [
# ...
"account", # Here
]
AUTH_USER_MODEL = 'account.CustomUser' # Here
Then, create "managers.py" just under "account" folder and create "CustomUserManager" class extending "UserManager" class in "managers.py" as shown below. *Just copy & paste the code below to "managers.py" and "managers.py" is necessary to make the command "python manage.py createsuperuser" work properly without any error:
# "account/managers.py"
from django.contrib.auth.models import UserManager
from django.contrib.auth.hashers import make_password
class CustomUserManager(UserManager): # Here
def _create_user(self, email, password, **extra_fields):
if not email:
raise ValueError("The given email must be set")
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.password = make_password(password)
user.save(using=self._db)
return user
def create_user(self, email=None, password=None, **extra_fields):
extra_fields.setdefault("is_staff", False)
extra_fields.setdefault("is_superuser", False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email=None, password=None, **extra_fields):
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)
if extra_fields.get("is_staff") is not True:
raise ValueError("Superuser must have is_staff=True.")
if extra_fields.get("is_superuser") is not True:
raise ValueError("Superuser must have is_superuser=True.")
return self._create_user(email, password, **extra_fields)
Then, create "CustomUser" class extending "AbstractUser" class and remove "username" by setting it "None" and set "email" with "unique=True" and set "email" to "USERNAME_FIELD" and set "CustomUserManager" class to "objects" in "account/models.py" as shown below. *Just copy & paste the code below to "account/models.py":
# "account/models.py"
from django.db import models
from django.contrib.auth.models import AbstractUser
from .managers import CustomUserManager
class CustomUser(AbstractUser):
username = None # Here
email = models.EmailField('email address', unique=True) # Here
USERNAME_FIELD = 'email' # Here
REQUIRED_FIELDS = []
objects = CustomUserManager() # Here
class Meta:
verbose_name = "custom user"
verbose_name_plural = "custom users"
Or, you can also create "CustomUser" class extending "AbstractBaseUser" and "PermissionsMixin" classes as shown below. *This code below with "AbstractBaseUser" and "PermissionsMixin" classes is equivalent to the code above with "AbstractUser" class and as you can see, the code above with "AbstractUser" class is much less code:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.utils import timezone
from .managers import CustomUserManager
class CustomUser(AbstractBaseUser, PermissionsMixin):
first_name = models.CharField("first name", max_length=150, blank=True)
last_name = models.CharField("last name", max_length=150, blank=True)
email = models.EmailField('email address', unique=True)
is_staff = models.BooleanField(
"staff status",
default=False,
help_text="Designates whether the user can log into this admin site.",
)
is_active = models.BooleanField(
"active",
default=True,
help_text=
"Designates whether this user should be treated as active. "
"Unselect this instead of deleting accounts."
,
)
date_joined = models.DateTimeField("date joined", default=timezone.now)
USERNAME_FIELD = 'email'
objects = CustomUserManager() # Here
Then, create "forms.py" just under "account" folder and create "CustomUserCreationForm" class extending "UserCreationForm" class and "CustomUserChangeForm" class extending "UserChangeForm" class and set "CustomUser" class to "model" in "Meta" inner class in "CustomUserCreationForm" and "CustomUserChangeForm" classes in "account/forms.py" as shown below. *Just copy & paste the code below to "forms.py":
# "account/forms.py"
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = CustomUser
fields = ('email',)
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = ('email',)
Then, create "CustomUserAdmin" class extending "UserAdmin" class and set "CustomUserCreationForm" and "CustomUserChangeForm" classes to "add_form" and "form" respectively and set "AdminPasswordChangeForm" class to "change_password_form" then set "CustomUser" and "CustomUserAdmin" classes to "admin.site.register()" in "account/admin.py" as shown below. *Just copy & paste the code below to "account/admin.py":
from django.contrib import admin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from django.contrib.auth.forms import AdminPasswordChangeForm
from django.contrib.auth.admin import UserAdmin
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
fieldsets = (
(None, {"fields": ("password",)}),
("Personal info", {"fields": ("first_name", "last_name", "email")}),
(
"Permissions",
{
"fields": (
"is_active",
"is_staff",
"is_superuser",
"groups",
"user_permissions",
),
},
),
("Important dates", {"fields": ("last_login", "date_joined")}),
)
add_fieldsets = (
(
None,
{
"classes": ("wide",),
"fields": ("email", "password1", "password2"),
},
),
)
add_form = CustomUserCreationForm # Here
form = CustomUserChangeForm # Here
change_password_form = AdminPasswordChangeForm # Here
list_display = ("email", "first_name", "last_name", "is_staff")
list_filter = ("is_staff", "is_superuser", "is_active", "groups")
search_fields = ("first_name", "last_name", "email")
ordering = ("email",)
filter_horizontal = (
"groups",
"user_permissions",
)
admin.site.register(CustomUser, CustomUserAdmin) # Here
Then, run the command below to make migrations and migrate:
python manage.py makemigrations && python manage.py migrate
Then, run the command below to create a superuser:
python manage.py createsuperuser
Then, run the command below to run a server:
python manage.py runserver 0.0.0.0:8000
Then, open the url below:
http://localhost:8000/admin/login/
Finally, you can log in with "email" and "password" as shown below:
And this is "Add custom user" page as shown below:
For Django 2
username = get_object_or_404(User, email=data["email"]).username
user = authenticate(
request,
username = username,
password = data["password"]
)
login(request, user)
Authentication with Email For Django 2.x
def admin_login(request):
if request.method == "POST":
email = request.POST.get('email', None)
password = request.POST.get('password', None)
try:
get_user_name = CustomUser.objects.get(email=email)
user_logged_in =authenticate(username=get_user_name,password=password)
if user_logged_in is not None:
login(request, user_logged_in)
messages.success(request, f"WelcomeBack{user_logged_in.username}")
return HttpResponseRedirect(reverse('backend'))
else:
messages.error(request, 'Invalid Credentials')
return HttpResponseRedirect(reverse('admin_login'))
except:
messages.warning(request, 'Wrong Email')
return HttpResponseRedirect(reverse('admin_login'))
else:
if request.user.is_authenticated:
return HttpResponseRedirect(reverse('backend'))
return render(request, 'login_panel/login.html')
If You created Custom database, from there if you want to validate your email id and password.
Fetch the Email id and Password with models.objects.value_list('db_columnname').filter(db_emailname=textbox email)
2.assign in list fetched object_query_list
3.Convert List to String
Ex :
Take the Html Email_id and Password Values in Views.py
u_email = request.POST.get('uemail')
u_pass = request.POST.get('upass')
Fetch the Email id and password from the database
Email = B_Reg.objects.values_list('B_Email',flat=True).filter(B_Email=u_email)
Password = B_Reg.objects.values_list('Password',flat=True).filter(B_Email=u_email)
Take the Email id and password values in the list from the Query value set
Email_Value = Email[0]
Password_Value=Password[0]
Convert list to String
string_email = ''.join(map(str, Email_Value))
string_password = ''.join(map(str, Password_Value))
Finally your Login Condition
if (string_email==u_email and string_password ==u_pass)
The default user model inherits/ Extends an Abstract class. The framework should be lenient to a certain amount of changes or alterations.
A simpler hack is to do the following:
This is in a virtual environment
Go to your django installation location and find the Lib folder
navigate to django/contrib/auth/
find and open the models.py file. Find the AbstractUser class line 315
LINE 336 on the email attribute add unique and set it to true
email = models.EmailField(_('email address'), blank=True,unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
Done, makemigrations & migrate
Do this at you own risk,
Pretty simple. There is no need for any additional classes.
When you create and update a user with an email, just set the username field with the email.
That way when you authenticate the username field will be the same value of the email.
The code:
# Create
User.objects.create_user(username=post_data['email'] etc...)
# Update
user.username = post_data['email']
user.save()
# When you authenticate
user = authenticate(username=post_data['email'], password=password)

Why is this Django form bypassing my custom manager when creating a new object?

I have a basic Django ModelForm to create a new user:
class UserCreationForm(forms.ModelForm):
class Meta:
model = User
# stuff here
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
if commit:
user.save()
return user
I also have a custom UserManager for handling the User creation function, which also creates a UserProfile and attaches it to the User:
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
"""Create a standard user."""
email = self.normalize_email(email)
user = self.model(email=email)
user.set_password(password)
user.save()
profile = UserProfile()
profile.user = user
profile.save()
return user
class User(AbstractBaseUser, PermissionsMixin):
objects = UserManager()
However, whenever the UserCreationForm is called successfully, it creates the User, but doesn't create the UserProfile.
My question is, why is the UserCreationForm bypassing my custom UserManager? Is there some special syntax I need to give the form to tell it my model has a custom manager?
I am also using django.views.generic.CreateView as the view, so I guess I could change the post method manually to create a User and UserProfile, but I'd like to know why this is failing before coming up with some hacky fix considering it seems like a very basic operation.
Thanks

Categories