How to Allow Superusers to access Django Admin Panels - python-3.x

I have the below code for Custom Users Model.
Can anyone help me out me with a Solution to restrict Access to Admin Site for Super Users only . Thanks in advance
# UserManager is for Custom User Model to override Django's Default Model
class UserManager(BaseUserManager):
def _create_user(self, email, password, is_superuser, **extra_fields):
if not email or not password:
raise ValueError("The given username or password must not be null")
user = self.model(
email=email,
password=password,
is_superuser=is_superuser,
last_login=now,
**extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
return self._create_user(email, password, False, **extra_fields)
def create_superuser(self, email, password=None, **extra_fields):
return self._create_user(email, password, True, **extra_fields)
class Users(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
created_at_utc = models.DateTimeField(auto_now_add=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['password']
def __str__(self):
return self.email
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 self.is_admin
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
class Meta:
db_table = "users"
I have the above code for Users, and following Code for Admin Panel to create and update User's
Can anyone help me out me with a Solution to restrict Access to Admin Site for Super Users only . Thanks in advance
class UserCreateForm(UserCreationForm):
class Meta:
model = Users
fields = (
"email","is_admin","is_superuser",
)
class UserChangeForm(BaseUserChangeForm):
class Meta:
model = Users
fields = (
"email","is_admin",
)
class UserAdmin(BaseAdmin):
form = UserChangeForm
add_form = UserCreateForm
fieldsets = (
(None, {"fields": ("email", "password","is_active","is_admin","is_superuser")}),
)
add_fieldsets = (
(None, {
"classes": ("wide",),
"fields": ("email", "password1", "password2","is_active","is_admin","is_superuser")}
),
)
filter_horizontal = ()
list_display = ("email","is_active", )
list_filter = ("is_active", )
search_fields = ("email",)
ordering = ("email",)
# Register your models here.
admin.site.register(Users, UserAdmin)
I have tried many solutions to restrict only SuperUser's to access the Admin Page when Login details are given. Can anyone help me out me with a Solution to restrict Access to Admin Site for Super Users only . Thanks in advance

I think what you are looking for field is is_staff which is there in
class AbstractUser(AbstractBaseUser, PermissionsMixin):
you can import this user from
from django.contrib.auth.models import AbstractUser
and you will find that it has field named as is_staff, so this is basically boolean field which determines if user has access to login to admin site or not, for more info do google search or find the article below
https://www.webforefront.com/django/adminpermissions.html
I see that you have created function as def is_staff(self): but you are not using field is_staff

Had the same issue. Instead of password=None, change it to password. And pass password=password into the create_user function as you see below, together with username=username:
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, password):
if not email:
raise ValueError('Please add an email address')
if not username:
raise ValueError('Please add an username')
user = self.model(email=self.normalize_email(
email), username=username, password=password)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user = self.create_user(email=self.normalize_email(
email), username=username, password=password)
user.is_active = True
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
Hope it works for you

Related

How to create a custom user model with an email and/or a phone number as a login with Django REST framework?

I want to create the custom user model with the email and/or the phone number as a login. I understood how make them separately but how to combine them together?
For instance, should i do the same like this but instead of the email the phone number?
Managers.py :
rom django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _
class CustomUserManager(BaseUserManager):
"""
Custom user model manager where email is the unique identifiers
for authentication instead of usernames.
"""
def create_user(self, email, password, **extra_fields):
"""
Create and save a User with the given email and password.
"""
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
"""
Create and save a SuperUser with the given email and password.
"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', 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)
Models.py:
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from .managers import CustomUserManager
class CustomUser(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
spouse_name = models.CharField(blank=True, max_length=100)
date_of_birth = models.DateField(blank=True, null=True)
def __str__(self):
return self.email
settings.py:
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = '/?verification=1'
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/?verification=1'
Thanks in advance, when you write an answer if you don't mind add a link to a useful material

The serializer always return none. Why?

The serializer always return none. Why?? Creating custom models time?
File views.py
print password = None
class UserLoginView(APIView):
def post(self, request, format=None):
serializer = UserLoginSerializer(data=request.data,)
if serializer.is_valid(raise_exception=True):
email = serializer.data.get('email')
password = serializer.data.get('password')
**print(password)**
print(request.data)
print(serializer.data)
user = authenticate(email=email, password=password)
print(user)
return Response({'msg':'successful login'}, status=status.HTTP_200_OK)
File Serializer.py
class UserLoginSerializer(serializers.ModelSerializer):
email = serializers.EmailField(max_length=255)
class Meta:
model = User
fields = ['email', 'password',]
extra_kwargs={
'password':{'write_only': True},
}
File Models.py
class UserManager(BaseUserManager):
def create_user(self, email, number, name, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
if not number:
raise ValueError('Users must have an email address')
user = self.model(
email = self.normalize_email(email),
number = number,
name = name,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, number, name, password=None):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(
email,
number = number,
password = password,
name = name,
)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
number=models.CharField(max_length=10)
name=models.CharField(max_length=30)
is_admin = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name','number']
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return self.is_admin
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?"
# Simplest possible answer: All admins are staff
return self.is_admin
Output
Quit the server with Ctrl + Break.
**None**
{'email': 'g#gmail.com', 'password': '123'}
{'email': 'g#gmail.com'}
**None**
\[06/Feb/2023 18:53:52\] "POST /api/user/login/ HTTP/1.1" 200 26**your text**
Try this:
email=serializer.data['email']
password=serializer.data['password']

Django custom model Interger extrafield not saving in the database return None instead

my models
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
print(phone_number, 'phone_number')
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
**extra_fields
)
user.phone_number = phone_number
# user.phone_number = 333333
print(user, 'user')
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, email, password):
"""
Creates and saves a staff user with the given email and password.
"""
user = self.create_user(
email,
password=password,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.create_user(
email,
password=password,
)
user.staff = True
user.admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
username = models.CharField(max_length=100, default="")
phone_number = models.IntegerField(default=0, verbose_name='phoneNumber')
is_active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
slug = models.SlugField(max_length=255, unique=True)
objects = UserManager()
def save(self, *args, **kwargs):
print(self.phone_number, 'before') #this print statement return none
if not self.slug:
self.slug = slugify(utils.rand_slug() + "-" + self.username)
super(User, self).save(*args, **kwargs)
print(self.phone_number, 'after') #this print statement return none
# notice the absence of a "Password field", that is built in.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = [] # Email & Password are required by default.
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __str__(self):
return self.email
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
#property
def owner(self):
return self.user
my serializer
class UserRegisterSerializer(ModelSerializer):
password = CharField(style={'input_type':'password'}, write_only=True)
token = SerializerMethodField(read_only=True)
expires = SerializerMethodField(read_only=True)
message = SerializerMethodField(read_only=True)
status_code = SerializerMethodField(read_only=True)
phone_number = IntegerField()
class Meta:
model =User
fields = [
'email',
'username',
'phone_number',
'token',
'slug',
'expires',
'message',
'status_code',
'password'
]
extra_kwargs = {'password': {'write_only':True}, 'email': {'required':True}}
def validate_phone_number(self, value):
print(value) #This print the actua phone_number serializer value
def get_status_code(self, obj):
data = 200
return data
def get_message(self, obj):
return 'Thank you for registering. Please verify your email before continuing'
def get_token(self, obj):
user = obj
token = get_tokens_for_user(user)
return token
def validate_email(self,value):
qs = User.objects.filter(email__iexact=value)
if qs.exists():
raise ValidationError("User with this email already exists")
return value
def validate_username(self, value):
qs = User.objects.filter(username__iexact=value)
if qs.exists():
raise ValidationError("User with this username already exists")
return value
def create(self, validated_data):
user_obj = User(
username=validated_data.get('username'),
email=validated_data.get('email')
)
user_obj.set_password(validated_data.get('password'))
user_obj.save()
return user_obj
def get_expires(self, obj):
return timezone.now() + timedelta(minutes=5) - datetime.timedelta(seconds=200)
my Views
class RegisterAPIView(generics.CreateAPIView):
queryset = User.objects.all()
serializer_class = UserRegisterSerializer
permission_classes = [AnonPermissionOnly]
after sending a post man request to that endpoint this is the response
{
"email": "philipssevarist#gmail.com33w4dd636",
"username": "philipsd34d6364433564w3",
"phone_number": 0,
"token": {
"refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY1MjI2NDI4NSwiaWF0IjoxNjUyMTc3ODg1LCJqdGkiOiI3ZjBjYjBhZTY5YWE0YzIzYjU4YTc1MWQ3N2M3YWVmZiIsInVzZXJfaWQiOjMzfQ.gLderlN9eMSkjpvaIg6I3eIuiGvo6Xzs_1lhq9hvKQ8",
"access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjUyMTc4MTg1LCJpYXQiOjE2NTIxNzc4ODUsImp0aSI6IjEzNWJiOTNkN2I2YzRlNzlhOTgxM2I4ODA2ODEyNjJjIiwidXNlcl9pZCI6MzN9.US3prDUaNNY9bChNakzRFO8MUam_HIQ_w5UI9_vDIgc"
},
"slug": "vl1yyt-philipsd34d6364433564w3",
"expires": "2022-05-10T10:19:45.407716Z",
"message": "Thank you for registering. Please verify your email before continuing",
"status_code": 200
Note:that phone_number returns 0 which is the default value
fortunately if i manuall add the phone number using my admin dashboard it works but when eve i try using a form or service like postman it doesn'work
i finally discovered what the problem was, so i be posting the answer so anyone who encounters it my find it useful, the problem is i was overiding the create method in my serializer, i passed in the email, password and username but not phone_number to the model create method, though the phone_number field in the forms was getting the value, it wasn't saving it to the database, because i wasn't creating it,
so the proper thing should have been
def create(self, validated_data):
user_obj = User(
username=validated_data.get('username'),
email=validated_data.get('email'),
phone_number = validated_data.get('phone_number')
)
user_obj.set_password(validated_data.get('password'))
user_obj.save()
return user_obj

Django PostgreSQL - the password isn't saved to the database

I have a custom User model and a function in views.py to handle the registration. when I register a user with Postman for example all the user data is stored in the database correctly but the password -field remains empty. I think that causes the problem when I try to use a simple login -page - it never accepts my credentials (because there is no password in the database). Any ideas why the password isn't saved and how to fix it?
I have a function like this in views.py when registering a new user:
def register(response):
if response.method == 'POST':
form = RegisterForm(response.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db()
user.id = form.cleaned_data.get('id')
user.save()
username = form.cleaned_data.get('email')
password = form.cleaned_data.get('password')
user = authenticate(username=email, password=password)
return HttpResponse(status=201)
else:
form = RegisterForm()
return HttpResponse(status=400)
And this is my custom user model:
class UserManager(BaseUserManager):
def create_user(self, email, password):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('A user must have a email.')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
Edit. Here is my RegisterForm:
User = get_user_model()
class RegisterForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
password_2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)
class Meta:
model = User
fields = ['email', 'id', 'gender', 'height', 'weight']
def clean_email(self):
'''
Verify email is available.
'''
email = self.cleaned_data.get('email')
qs = User.objects.filter(email=email)
if qs.exists():
raise forms.ValidationError("email is taken")
return email
def clean_id(self):
'''
Verify id is available.
'''
id = self.cleaned_data.get('id')
qs = User.objects.filter(id=id)
if qs.exists():
raise forms.ValidationError("id is taken")
return id
def clean(self):
'''
Verify both passwords match.
'''
cleaned_data = super().clean()
password = cleaned_data.get("password")
password_2 = cleaned_data.get("password_2")
if password is not None and password != password_2:
self.add_error("password_2", "Your passwords must match")
return cleaned_data
And here is the model:
class CustomUser(AbstractBaseUser):
is_active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
gender = models.CharField(null=True, blank=True, max_length=20)
height = models.CharField(null=True, blank=True, max_length=3)
id = models.CharField(primary_key=True, unique=True, blank=False, max_length=100)
email= models.EmailField(max_length=100, unique=True, null=False, blank=False)
weight = models.CharField(max_length=3, null=True, blank=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = [] # Email & Password are required by default.
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __str__(self):
return self.email
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()
And soon after editing my question I noticed I was missing the save function from the RegisterForm class. Adding this solved the problem:
def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data["password"])
if commit:
user.save()
return user

Django login/register issue

I am new to Django and am building a database-driven website using PyCharm.
I am having an issue with users registering/logging in. What is happening is, when a user registers, I check the "Database" tab to the right, and the information will be passed into a table named "SavBlock_user", which will have the users name, password, etc.. Then, when I try to log in, it won't allow me to login due to incorrect username/password. However, if I try to login using a username/password from a different table named "auth_user" (like username: admin / password: admin), then I can successfully login. I'm not sure how to fix this.
Ideally, what I would like to do is completely remove the "SavBlock_user" table and strictly use "auth_user" for all of my users, but I'm not sure how to do this. I may have created a 'custom' user model back when I was learning the system, but I can't remember.
My files:
Project\register\forms.py
from django import forms
from SavBlock.models import * # <--- Contains User
''' Form for users to register '''
class RegisterForm(forms.ModelForm):
email = forms.EmailField(
initial='myemail#savagez.com'
)
uso_validate = forms.BooleanField(
label='Are you a PSMC member? (Chief, Uso, Anak)',
initial=False
)
class Meta:
model = User
widgets = {
'password': forms.PasswordInput(),
}
fields = '__all__'
Project\register\views.py
from django.http import request
from django.shortcuts import render, redirect
from .forms import RegisterForm
# Create your views here.
def register(response):
if response.method == "POST":
form = RegisterForm(response.POST or None)
if form.is_valid():
form.save()
return redirect('/dashboard/')
else:
form = RegisterForm()
return render(response, 'register/register.html', {'form': form})
Project\SavBlock\models.py
from django.db import models
class User(models.Model):
username = models.CharField("user name", max_length=50, default='')
email = models.EmailField("email address", unique=True, default='DEFAULT VALUE')
first_name = models.CharField("first name", max_length=50)
last_name = models.CharField("last name", max_length=50)
password = models.CharField("password", unique=True, max_length=50, default='')
rank = {
0: 'Supporter',
1: 'Anak',
2: 'Uso',
3: 'Chief'
}
#TODO: FIT __INIT__
'''
def __init__(self, first_name, last_name, *args, **kwargs):
super().__init__(*args, **kwargs)
self.first_name = first_name.title()
self.last_name = last_name.title()
'''
# Magic method returns string of self
def __str__(self):
return f"User {self.first_name} {self.last_name} rank {self.rank}".strip()
#property
def get_full_name(self):
return f"{self.first_name} {self.last_name}".strip()
class Anak(User):
def __init__(self, first_name, last_name, tribe):
super().__init__(first_name, last_name)
self.tribe = tribe.title()
self.rank = User.rank[1]
class Uso(User):
def __init__(self, first_name, last_name, tribe):
super().__init__(first_name, last_name)
self.tribe = tribe.title()
self.rank = User.rank[2]
----EDIT----
I fixed the different user tables and basically reset the migrations. Now, all users are showing up under a single user table SavBlock_user. However, the login issue is still there.
Admin was created using the terminal manage.py createsuperuser command. I am able to login on the webpage using this account.
testing123 was created using the registration form. It pulls up a message that says "Please enter a correct username and password".
Anyone have any ideas?

Resources