The serializer always return none. Why? - python-3.x

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']

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

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

drf CustomUser matching query does not exist

i'm working on mobile app with customuser. i'm trying to send otp on mail while creating user and set is_verify to false and after that user verify with otp then is_verify will set to true but if user does't verify otp add closes app then again while signup we're adding check if user exist and is_verified to true then return already exist otherwise create user and send otp again. so i'm getting error on if user doesnotexist then its showing this error:
users.models.CustomUser.DoesNotExist: CustomUser matching query does not exist.
and its getting this error from except customuser.doesnotexist block
models.py:
class CustomUser(AbstractBaseUser, PermissionsMixin):
first_name = models.CharField(_('first name'), max_length=50)
last_name = models.CharField(_("last name"), max_length=50)
email = models.EmailField(_('email address'), unique=True)
mobile_number = models.CharField(
_('mobile number'), max_length=12, unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
user_type = models.IntegerField(_("user_type"))
otp = models.CharField(_("otp"), max_length=10, default="0")
is_verified = models.BooleanField(default=False)
USER_TYPE_CHOICES = (
(1, 'users'),
(2, 'courier'),
(3, 'admin'),
)
user_type = models.PositiveSmallIntegerField(
choices=USER_TYPE_CHOICES, null=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserMananager()
def __str__(self):
return self.email
seralizers.py:
class CustomUserSerializer(serializers.ModelSerializer):
profile = UserProfileSerializer(required=False)
password = serializers.CharField(write_only=True, required=False)
class Meta:
model = CustomUser
fields = ('id', 'first_name', 'last_name', 'email',
'mobile_number', 'password', 'is_active', 'user_type', 'otp', 'profile')
def create(self, validated_data):
profile_data = validated_data.pop('profile', None)
user = CustomUser(
email=validated_data['email'],
mobile_number=validated_data['mobile_number'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
user_type=validated_data['user_type'],
)
user.set_password(validated_data['password'])
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
otp = random_with_N_digits(5)
user.otp = otp
user.is_active = False
user.save()
subject = 'Please Confirm Your Account'
message = 'Your 5 Digit Verification Pin: {}'.format(otp)
email_from = '*****'
recipient_list = [str(user.email), ]
send_mail(subject, message, email_from, recipient_list)
#user = CustomUser.objects.create(**validated_data)
# if profile_data:
UserProfile.objects.create(
user=user, age=None, gender=None)
return user
def update(self, instance, validated_data):
profile_data = validated_data.pop('profile', None)
# update user data
instance.first_name = validated_data.get(
'first_name', instance.first_name)
instance.last_name = validated_data.get(
'last_name', instance.last_name)
instance.email = validated_data.get('email', instance.email)
instance.save()
password = validated_data.get('password', None)
if password:
instance.set_password(password)
instance.save()
return instance
views.py:
#api_view(["POST"])
#permission_classes((AllowAny,))
def register(request):
try:
user = CustomUser.objects.get(
email=request.data.get('email'), is_verified=True)
if user:
return Response({'message': 'Customer with this mail already exists', 'status': 'false', 'status_code': status.HTTP_401_UNAUTHORIZED, 'currentTimeStamp': datetime.datetime.now()}, status=status.HTTP_400_BAD_REQUEST)
except CustomUser.DoesNotExist:
serializer = CustomUserSerializer(data=request.data)
if serializer.is_valid():
user = serializer.save()
token, created = Token.objects.get_or_create(user=user)
current_time = datetime.datetime.now()
return Response({'status_code': status.HTTP_200_OK, 'status': 'true', 'currentTimeStamp': current_time, 'message': 'User registered successfully, OTP sent to your Mail', 'data': {'id': user.id, 'token': token.key, 'user_type': user.user_type}}, status=status.HTTP_200_OK)
return Response({'message': serializer.errors, 'status': 'false', 'status_code': status.HTTP_401_UNAUTHORIZED, 'currentTimeStamp': datetime.datetime.now()}, status=status.HTTP_400_BAD_REQUEST)
it seems it showing error after after this check:
user = CustomUser.objects.get(email=email)
but as i have already created the user with serializer.save so it should be getting the current user
edit:
i solved it by saving serailizer.save object to user but i'm still stuck in this situation as i want to send mail everytime until user is_verified is true but after first registration its showing customuser already exist . its only checking email field as its comes with django is there any to override this so it should show customuser exist only if email and is_verified is true

How to Allow Superusers to access Django Admin Panels

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

Resources