Cannot log my superuser in ( custom user model / manager ) - python

I'm trying to build super user using a custom user model and a custom user manager. I did exactly the same thing than the django doc about the create_superuser method and in my shell, I'm able to create a superuser with an email and a password. But when I try to log in on the django admin page, I have this wierd error :
Please enter the correct email and password for a staff account. Note
that both fields may be case-sensitive.
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.db import models
from multiselectfield import MultiSelectField
class UserManager(BaseUserManager):
#custom create_user method
def create_user(self, email, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email = self.normalize_email(email)
)
user.set_password = password
user.save(using=self._db)
return user
#Custom create_super_user method
def create_superuser(self, email, password=None):
user = self.create_user(
email = self.normalize_email(email),
password = password
)
user.admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
#setting up Choices for interest, Must add other fields ...
MATHS = 'mat'
PHYSICS = 'phy'
HISTORY = 'his'
BIOLOGIE = 'bio'
ECONOMICS = 'eco'
POLITICS = 'pol'
MUSIC = 'mus'
ENGLISH = 'eng'
FRENCH = 'fra'
SPANISH = 'spa'
LAW = 'law'
COMPUTER_SCIENCE = 'cs'
COMMUNICATION = 'com'
MARKETING = 'mar'
SPORT = 'spo'
INTERESTS_CHOICES = (
(MATHS, 'Maths'),
(PHYSICS, 'Physics'),
(HISTORY, 'History'),
(BIOLOGIE, 'Biologie'),
(ECONOMICS, 'Economics'),
(POLITICS, 'Politics'),
(MUSIC, 'Music'),
(ENGLISH, 'English'),
(FRENCH, 'French'),
(SPANISH, 'Spanish'),
(LAW, 'Law'),
(COMPUTER_SCIENCE, 'Computer Science'),
(COMMUNICATION, 'Communication'),
(MARKETING, 'Marketing'),
(SPORT, 'Sport')
)
interests = MultiSelectField(
max_length = 2,
choices = INTERESTS_CHOICES
)
#Setting up a Ranking System
RANKING_CHOICES = [
('silver', 'Silver'),
('gold', 'Gold'),
('platinium', 'Platinium'),
('diamond', 'Diamond')
]
email = models.EmailField(
max_length=50,
unique=True
)
username = models.CharField(
max_length=25,
unique=True,
null=True,
blank=True
)
date_joined = models.DateTimeField(auto_now_add=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=70)
birth_date = models.DateField(null=True, blank=True)
reputation = models.PositiveIntegerField(default=0)
active = models.BooleanField(default=True)
rank = models.CharField(choices=RANKING_CHOICES, max_length=1)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
bio = models.TextField(
max_length=300,
default="",
blank=True
)
objects = UserManager()
#Setting email to be the main source of authentication
USERNAME_FIELD = 'email'
#Super User Only
REQUIRED_FIELDS = ['password']
#def get_absolute_url(self):
#use reverse + nom de l'url de view
def __str__(self):
return self.email
def get_full_name(self):
return f"{self.first_name} {self.last_name}"
def get_short_name(self):
return self.first_name
def get_username(self):
return self.username
def set_user_league(self):
if 15 <= self.reputation < 40:
self.rank = "gold"
elif 40 <= self.reputation < 80:
self.rank = "platinium"
else:
self.rank = "diamond"

You set a password by calling .set_password(..), not assigning a new value:
class UserManager(BaseUserManager):
#custom create_user method
def create_user(self, email, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email = self.normalize_email(email)
)
user.set_password(password)
user.save(using=self._db)
return user
The default create_superuser will set is_staff and is_superuser to True as well:
#Custom create_super_user method
def create_superuser(self, email, password=None):
user = self.create_user(
email = self.normalize_email(email),
password = password
)
user.admin = user.is_superuser = user.is_staff = True
user.save(using=self._db)
return user

We need to set the flag is_superuser to True, in order to make user a superuser in system. Please find the below code:
def create_superuser(self, email, password):
"""
create and save superuser
"""
user = self.create_user(
self.normalize_email(email), password=password)
user.is_staff = True
user.is_superuser = True
user.admin = True
user.save(using=self._db)
return user

Related

Can't access Django Admin with my Custom User credentials

I created an app 'accounts' from which I created my CustomUser. Then, I created superuser from the command line successfully. But I can't login to Django Admin. Everytime, it displays "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive."
This is my accounts.models file, The only one I modified.
from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import User
class MyUserManager(BaseUserManager):
def create_user(self, username, email, password=None):
if not email:
raise ValueError()
if not username:
raise ValueError()
user = self.model(email=self.normalize_email(email), username=username)
user.set_password(password)
user.save()
return user
def create_superuser(self, username, email, password=None):
user = self.create_user(username=username, email=email, password=None)
user.admin = True
user.staff = True
user.superuser = True
user.save()
return user
class CustomUser(AbstractBaseUser):
username = models.CharField(max_length=12, primary_key=True, unique=True)
id = models.IntegerField(default=1)
email = models.EmailField(max_length=255, blank=False, unique=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
superuser = models.BooleanField(default=False)
USERNAME_FIELD = "username"
REQUIRED_FIELDS = ['email']
objects = MyUserManager()
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
#property
def is_staff(self):
return self.staff
#property
def is_superuser(self):
return self.superuser
#property
def is_active(self):
return self.active
Copy-Paste is your problem:
def create_superuser(self, username, email, password=None):
user = self.create_user(username=username, email=email, password=password) # here was password=None
# other staff

Django authentication always return none

My authentication doesn't seem to work. I got registration and everything, its just the log in and authenticate aspect that doesnt work. I'm not sure why.
I'm not sure as to why my django auth returns none.
I have this in my settings:
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'UniLinkedApp.auth.MyAuthBackEnd',
)
I have my models as:
class Register(models.Model):
username = models.CharField(max_length = 200)
email = models.EmailField(max_length = 200)
password = models.CharField(max_length = 200)
university = models.CharField(max_length=50)
major = models.CharField(max_length = 200)
def __str__(self):
return self.user
class MyAccountManager(BaseUserManager):
def create_user(self, username, email, password, university, major):
if not email:
raise ValueError("Users must have an email address")
if not username:
raise ValueError("Users must have an username")
user = self.model(
username=username,
email=self.normalize_email(email),
password = password,
university = university,
major = major,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user = self.create_user(
username=username,
email=self.normalize_email(email),
password=password,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
username = models.CharField(max_length = 200)
email = models.EmailField(max_length = 200)
password = models.CharField(max_length = 200)
university = models.CharField(max_length=50)
major = models.CharField(max_length = 200)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=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 = 'username'
objects = MyAccountManager()
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
I have my forms like:
class RegisterForm(forms.ModelForm):
password = forms.CharField(label='Password', widget=forms.PasswordInput)
class Meta:
model = Account
fields = ['username', 'email', 'password', 'university', 'major']
class AccountAuthenticationForm(forms.ModelForm):
password = forms.CharField(label='Password', widget=forms.PasswordInput)
class Meta:
model = Account
fields = ('username', 'email','password', 'university', 'major')
def clean(self):
if self.is_valid():
email = self.cleaned_data['email']
password = self.cleaned_data['password']
if not authenticate(email=email, password=password):
raise forms.ValidationError("Invalid login")
My auth is:
class MyAuthBackEnd(ModelBackend):
def authenticate(self, **kwargs):
username = kwargs['username']
password = kwargs['password']
try:
account = Account.objects.get(username=username)
if account.check_password(password) is True:
return account
except Account.DoesNotExist:
pass
It doesn't matter what authentication method I use, it still returns none despite having correct username and password.
I tried all sorts of things but not sure how to fix it.
This is my login as method:
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = MyAuthBackEnd.authenticate(request, username=username, password = password)
#print(user)
#print(username, password)
if user is not None:
print('Test')
login(request, username)
return redirect('home')
else:
messages.info(request, 'Username or Password is incorrect')

Django Views filter objects by user from custom model

I've created custom user model, and i'm trying to filter data in views.py by that user.
The error i get is:
'SomeClassView' object has no attribute 'user'
My goal is to 'encapsulate' data for each user.
user model:
class CustomUserManger(BaseUserManager):
use_in_migrations = True
def create_user(self, email, username, password, **other_fields):
email = self.normalize_email(email)
user = self.model(email=email, username=username, **other_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password, **other_fields):
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_superuser', True)
other_fields.setdefault('is_active', True)
if other_fields.get('is_staff') is not True:
raise ValueError('Superuser must be assigned to staff')
if other_fields.get('is_superuser') is not True:
raise ValueError('Superuser must be assigned to superusers')
return self.create_user(email, username, password, **other_fields)
class User(AbstractUser, PermissionsMixin):
username = models.CharField(_('username'), max_length=20, unique=True)
email = models.EmailField(unique=True)
password = models.CharField(max_length=128)
is_staff = models.BooleanField(default=True)
is_active = models.BooleanField(default=True)
objects = CustomUserManger()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __str__(self):
return self.username
Views:
class SomeClassView(viewsets.ModelViewSet):
user = SomeClass.user
serializer_class = WagonSerializer
authentication_classes = (SessionAuthentication, )
#login_required
def get_queryset(self):
user = self.request.user
return SomeClass.objects.filter(user=user)
Ok, i forgot that my react app doesn't put user to json, so in database user was null, that's why table was blank.

Link Customer Django user to group and give them permission

I customized the Django user model, now I can't link my users to Django groups to give them permissions
from django.db import models
from django.core.validators import RegexValidator
from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser, PermissionsMixin)
from django.db.models.signals import post_save
from django.contrib.auth.models import Group
USERNAME_REGEX = '^[a-zA-Z0-9.+-]*$'
class UserManager(BaseUserManager):
def create_user(self, username, email, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(username=username, email=self.normalize_email(email))
user.set_password(password)
user.save(using=self._db)
if group is not None:
group.user_set.add(user)
return user
# user.password = password # bad - do not do this
def create_superuser(self, username, email, password=None):
user = self.create_user(username, email, password=password)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
if group is not None:
group.user_set.add(user)
return user
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=300, validators=[
RegexValidator(regex=USERNAME_REGEX, message='Username must be alphanumeric or contain numbers',
code='invalid_username')],
unique=True)
email = models.EmailField(max_length=255, unique=True, verbose_name='email address')
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
def __str__(self):
return self.username
def get_short_name(self):
# The user is identified by their email address
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

Django : profile edition set_password()

I would like to create an API for a mobile application. In this application, we can create an account, and of course, edit our profile.
For create an account, I use the django account default model like that:
models.py:
def create_user(self, email, username, phone, deliveryAddress, postalCode, city, password=None):
if not email:
raise ValueError("Users must have an email address")
if not username:
raise ValueError('Users must have an username')
if not phone:
raise ValueError('Users must have a phone number')
if not deliveryAddress:
raise ValueError('Users must have a delivery Address')
if not postalCode:
raise ValueError("Users must have a postal code")
if not city:
raise ValueError('Users must have a city')
user = self.model(
email = self.normalize_email(email),
username = username,
phone = phone,
deliveryAddress = deliveryAddress,
postalCode = postalCode,
city = city,
)
user.set_password(password)
user.save(using = self._db)
return user
def create_superuser(self, email, username, phone, deliveryAddress, postalCode, city, password=None):
user = self.create_user(
email = self.normalize_email(email),
username = username,
password = password,
phone = phone,
deliveryAddress = deliveryAddress,
postalCode = postalCode,
city = city,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using = self._db)
class memberArea(AbstractBaseUser):
username = models.CharField(max_length=255)
email = models.EmailField(max_length=255, unique=True)
phone = models.TextField()
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
deliveryAddress = models.TextField()
postalCode = models.CharField(max_length=255)
forget = models.TextField(null=True, blank=True)
city = models.CharField(max_length=255)
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 = ['username', 'phone', 'deliveryAddress', 'postalCode', 'city']
objects = MyAccountManager()
def __str__(self):
return self.email + ' : ' + self.username
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
When I create an account, I automaticaly encrypt the user password with set_password()
Now, I want to make a view to edit an account.
Of course I want the password to be encrypted too.
This is my code:
serializer.py:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = memberArea
fields = ['username', 'email', 'phone', 'password', 'deliveryAddress', 'postalCode', 'city']
extra_kwargs = {
'password': {'write_only': True},
}
views.py:
#Edit account
#api_view(['PUT', ])
def edit_account(request, pk):
try:
account = memberArea.objects.get(pk=pk)
except memberArea.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'PUT':
serializer = AccountSerializer(account, data=request.data)
data = {}
if serializer.is_valid():
serializer.save()
data['response'] = 'Account updated with success !'
return Response(data)
return Response(serializer.errors)
I don't know where and how I can encrypt the password before updating the profile.
Maybe I can do that in my serializer file by finding the account that we want to edit but I don't know how to do that in this file...
Thanks by advance for your help
You can do Field-level validation in your serializer to encrypt the raw password to a hashed one.
Here is an example of encrypting the raw password in your AccountSerializer. Then, every raw password from a request's json payload will be encrypted to a hashed one.
from django.contrib.auth.hashers import make_password
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = memberArea
fields = ['username', 'email', 'phone', 'password', 'deliveryAddress', 'postalCode', 'city']
extra_kwargs = {
'password': {'write_only': True},
}
def validate_password(self, raw_password):
return make_password(raw_password)

Categories

Resources