Exception Value: local variable 'other_user' referenced before assignment - django

So, this is probably just something simple I'm doing wrong here. But basically, I am attempting to simply pass in the pk of the other_user. I tested that the query works correctly, and am indeed printing the other user. Just don't know where to place it correctly in my code so I can pass it to the render part.
local variable 'other_user' referenced before assignment
models.py
class ProfileManager(BaseUserManager):
def create_user(self, username, email,description,photo, password=None):
if not email:
raise ValueError("You must creat an email")
if not username:
raise ValueError("You must create a username!")
if not description:
raise ValueError("You must write a description")
if not photo:
raise ValueError("You must upload a photo")
user = self.model(
email=self.normalize_email(email),
username = username,
description= description,
photo= photo,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email,description,photo, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
description=description,
photo=photo,
)
user.is_admin=True
user.is_staff=True
user.is_superuser=True
user.save(using=self._db)
return user
class Profile(AbstractBaseUser):
class Meta:
swappable = 'AUTH_USER_MODEL'
email = models.EmailField(verbose_name="email")
username = models.CharField(max_length=30, 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)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
#what I added
description = models.TextField()
photo = models.ImageField(upload_to='profile_photo',blank=False, height_field=None, width_field=None, max_length=100)
matches = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='+', blank=True)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['description','photo','email']
objects = ProfileManager()
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
class Conversation(models.Model):
members = models.ManyToManyField(settings.AUTH_USER_MODEL)
class UserVote(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
voter = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='given_vote', on_delete=models.CASCADE)
vote = models.BooleanField(default=False)
class Meta:
unique_together = (('user', 'voter'))
class InstantMessage(models.Model):
sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE )
conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE)
message = models.TextField()
date = models.DateTimeField(verbose_name="Data creation",default=timezone.now(), null=False)
def __unicode__(self):
return self.message
#tests to see if messages are exclusive between sender, receiver (won't work with new model)
#classmethod
def find_messages_exclusive_to_profile(cls,sender,receiver):
#members = receiver AND sender, not receiver or sender
exclusive_conversations = Conversation.objects.filter(members= receiver ).filter(members= sender)
exclusive_messages = InstantMessage.objects.filter(conversation__in=exclusive_conversations)
return exclusive_messages
def message (request, profile_id):
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
form.save()
return redirect('dating_app:messages', other_user.id)
else:
conversation, created = Conversation.objects.filter(members = request.user).filter(members= profile_id).get_or_create()
print(conversation)
other_user = conversation.members.filter(id=profile_id).get()
print(other_user)
form = MessageForm({'sender': request.user, 'conversation': conversation})
context = {'form' : form }
return render(request, 'dating_app/message.html', context)

You can access the ModelForm's instance from form.instance and get value from there.
if form.is_valid():
form.save()
m = form.instance
return redirect('dating_app:messages', m.id)
You are mostly likely to also get the instance while saving it as
m = form.save()

Related

MultipleObjectsReturned at /profile/ get() returned more than one CustomUser -- it returned 2

CustomUser model is storing user account detail. After logging in, the particular user profile must be fetched using the token generated during signup.
I have made phone_number as the primary key and unique attribute is set to True. My code behaves properly when there is only one user but >1 user, data of all existing users are fetched which is why this error is showing up!
Here is the model structure
class CustomUser(AbstractUser):
first_name = models.CharField(null=True, blank=True, max_length= 50)
last_name = models.CharField(null=True, blank=True, max_length= 50)
username = models.CharField(null=True, blank=True, max_length= 12)
phone_number = models.CharField(primary_key=True, max_length= 10,unique=True)
dob = models.CharField(max_length=12, null=True, blank=True)
email = models.EmailField(null=True, blank=True)
address = models.CharField(max_length= 500,null=True, blank=True)
pincode = models.CharField(max_length=10, blank=True,null=True)
state = models.CharField(max_length= 256,null=True, blank=True)
district = models.CharField(max_length= 56,null=True, blank=True)
otp_verified = models.BooleanField(null=True,blank=True, default=False)
date_joined = models.DateTimeField(null=True,blank=True)
last_login = models.DateTimeField(null=True,blank=True)
loyality_level = models.IntegerField(null=True,blank=True)
loyality_points = models.IntegerField(null=True,blank=True)
gender = models.CharField(max_length= 2,null=True, blank=True)
user_type = models.CharField(max_length= 2,null=True, blank=True)
objects = MyUserManager()
search_fields = ("",)
USERNAME_FIELD = 'phone_number'
def __str__(self):
return self.phone_number
#property
def token(self):
return self._generate_jwt_token()
def _generate_jwt_token(self):
return str(AccessToken.for_user(self))
Here is my view for fetching Profile using APIView
class ProfileView(APIView):
authentication_class = [JWTAuthentication]
permission_classes = [IsAuthenticated]
try:
def get(self, request):
print(request)
user = model_to_dict(request.user)
print(user)
del user['password']
return Response({"ok": True, "userData": user},status=200)
except Exception as e:
print("::",e,"::")
Here is the view for user registration/signup
class CreateUserView(APIView):
permission_classes = (AllowAny, )
def post(self, request):
data = request.data
print(data)
first_name = data.get("first_name")
last_name = data.get("last_name")
email = data.get("email")
dob = data.get("dob")
phone_number = data.get("phone_number")
address = data.get("address")
pincode = data.get("pincode")
state = data.get("state")
district = data.get("district")
password = make_password(data.get("password"))
print(data)
try:
if not CustomUser.objects.filter(phone_number=phone_number).exists():
print(email)
print("entered")
if email == "":
user = CustomUser(
first_name=first_name,
last_name=last_name,
email=email,
dob=dob,
phone_number=phone_number,
address=address,
pincode=pincode,
state=state,
district=district,
password=password,
username="user"
)
user.save()
token = user.token
user = model_to_dict(user)
del user["password"]
else:
user = CustomUser(
first_name=first_name,
last_name=last_name,
email=email,
phone_number=phone_number,
address=address,
pincode=pincode,
state=state,
district=district,
password=password,
dob=dob,
username="user"
)
user.save()
token = user.token
user = model_to_dict(user)
del user["password"]
subject = 'Regarding new user registration'
message = f'Hurrah! your registration is officially complete with this process.'
email = EmailMessage(subject,message, to=[email])
email.send()
else:
return Response({"ok": False, "message": "Your number is already registered!"}, status=401)
except Exception as e:
return Response({"ok": False, "message": "Unsuccessful attempt!" + str(e)}, status=401)
return Response({"ok": True, "message": "User created and confirmation mail sent successfully!", "user": user, "token": token},status=200)
Here is the view for an user to login
class LoginView(APIView):
def post(self,request):
phone_number = request.data.get("phone_number")
password = request.data.get("password")
if CustomUser.objects.filter(phone_number=phone_number).exists():
user = CustomUser.objects.get(phone_number=phone_number)
if check_password(password, user.password):
return Response({"user":model_to_dict(user), "token":user.token}, status =200)
else:
return Response({"message":"Invalid credentials"}, status=401)
else:
return Response({"message":"Invalid credentials"}, status=401)
You have a method definition inside a try, thay's not ok. I think you meanth to put the try inside the method.
try:
def get(self, request):
print(request)
user = model_to_dict(request.user)
print(user)
del user['password']
return Response({"ok": True, "userData": user},status=200)
except Exception as e:
print("::",e,"::")

Django Rest Framework : Why Complex nested serializer tries to create nested fields in database when calling .is_valid()?

Context
I have a project in which there are three entities : Account, Community and JoinRequest.
A JoinRequest binds an Account (user) with a Community. And there should not be more than one JoinRequest for any couple (Account, Community).
Problem
I coded the respective models, serializers and unittest, which you can see below. But when I run my test, it fails when returning join_request_serializer.is_valid() = False
Which leads to the following error :
join_request_serializer.errors
{'user': {'email': [ErrorDetail(string='account with this email already exists.', code='unique')], 'username': [ErrorDetail(string='account with this username already exists.', code='unique')], 'password': [ErrorDetail(string='This field is required.', code='required')]}, 'community': {'name': [ErrorDetail(string='community with this name already exists.', code='unique')]}}
It seems the .is_valid() method of the JoinRequestSerializer tries to recreate an Account and a Community, whose data were previously passed as arguments at construction of the instance...
Any idea why this error appears?
Unit Test
class JoinRequestSerializerTestCase(TestCase):
def test_join_request_serializer_create_success(self):
account = register()
account_serializer = AccountSerializer(account)
community_data = {
'name': 'CommunityNameExample'
}
community = Community(community_data)
community_serializer = CommunitySerializer(community)
data = {'user':account_serializer.data, 'community':community_serializer}
join_request_serializer = JoinRequestSerializer(data=data)
self.assertEqual(join_request_serializer.is_valid(), True)
join_request_serializer.save()
self.assertEqual(JoinRequest.objects.count(), 1)
Account
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, password=None):
if not email:
raise ValueError('Users must have an email address')
if not username:
raise ValueError('Users must have an username')
user = self.model(
email=self.normalize_email(email),
username=username,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
# This method must be overridden to use MyAccountManager class
user = self.create_user(
email=self.normalize_email(email),
username=username,
password=password,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(
max_length=30,
unique=True,
validators = [
RegexValidator(
regex='^[a-zA-Z0-9]*$',
message='Username must be Alphanumeric.',
code='invalid_username'
)
]
)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now_add=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' # Generic (not explicit) keyword for the login field
REQUIRED_FIELDS = ['email']
objects = MyAccountManager() # What is the point of this line?
def create(self, email, username, password, **kwargs):
account = Account.objects.create_user(
username = username,
email = email,
password = password
)
post_save(sender=Account, instance=account, created = True, raw=True)
return account
Community
class Community(models.Model):
name = models.CharField(
max_length=30,
unique=True,
validators = [
RegexValidator(
regex='^[a-zA-Z0-9]*$',
message='Community name must be Alphanumeric.',
code='invalid_username'
)
]
)
bio = models.CharField(max_length=150, blank=True, default='')
slug = models.SlugField(max_length=30, blank=True, default=slugify(name))
class Meta(object):
verbose_name_plural = 'Communities'
def __str__(self):
return self.name
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Community, self).save(*args, **kwargs)
JoinRequest
class JoinRequest(models.Model):
community = models.ForeignKey(Community, on_delete=models.CASCADE)
user = models.ForeignKey(Account, on_delete=models.CASCADE)
creation_date = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=['community', 'user'], name='unique_joinrequest')
]
AccountSerializer
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ['email', 'username', 'password']
extra_kwargs = {'password':{'write_only':True}}
def create(self):
account = Account.objects.create_user(
email = self.validated_data['email'],
username = self.validated_data['username'],
password = self.validated_data['password'],
)
return account
CommunitySerializer
class CommunitySerializer(serializers.ModelSerializer):
class Meta:
model = Community
fields = ['name', 'bio']
lookup_field = 'slug'
extra_kwargs = {
'url':{'lookup_field':'slug'}
}
JoinRequestSerializer
class JoinRequestSerializer(serializers.ModelSerializer):
user = AccountSerializer(
source='account_set',
)
community=CommunitySerializer(
source='community_set',
)
class Meta:
model = JoinRequest
fields = ['user', 'community']
read_only_fields = ('user', 'community')
validators = [
UniqueTogetherValidator(
queryset=JoinRequest.objects.all(),
fields=['user', 'community'],
message='A Join Request for this couple of User'\
' and Community already exists.'
)
]
extra_kwargs = {
'user':{'read_only':True},
'commnuity':{'read_only':True}
}
def create(self):
join_request = JoinRequest(
user = self.validated_data['user'],
community = self.validated_data['community'],
)
return join_request

All usernames are indicated by the username phrase

admin dashboard:
In addition to the admin part, the template is displayed in the same way.
Ever since I customized the accounts section, in all the sections where I have used the username, there is a problem that the usernames are displayed without that name and only by displaying the phrase username.
settings.py:
AUTH_USER_MODEL = 'accounts.CustomUser'
models.py(accounts):
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, password=None):
if not email:
raise ValueError("Users must have an email address.")
if not username:
raise ValueError("Users must have a username.")
user = self.model(
email=self.normalize_email(email),
username=username
)
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_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
def get_profile_image_filepath(self, filepath):
return f'images/accounts/profiles/{self.pk}/{"profile.png"}'
class CustomUser(AbstractBaseUser, PermissionsMixin):
class Meta:
permissions = [
('all', 'all of the permissions')
]
first_name = models.CharField(max_length=30, null=True, blank=True)
last_name = models.CharField(max_length=30, null=True, blank=True)
email = models.EmailField(verbose_name='email', max_length=100, unique=True)
username = models.CharField(max_length=55, 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)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
profile_image = models.ImageField(null=True, blank=True, upload_to=get_profile_image_filepath, default='images/accounts/profiles/default_image.jpg')
objects = MyAccountManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
def __str__(self):
return self.USERNAME_FIELD
def get_profile_image_filename(self):
return str(self.profile_image)[str(self.profile_image).index(f'images/accounts/profiles/{self.pk}/'):]
def get_absolute_url(self):
return reverse("accounts:user_view", args=[str(self.id)])
models.py(news):
class News(models.Model):
class Meta:
permissions = [
('all', 'all of the permissions')
]
ordering = ['-date']
title = models.CharField(max_length=255)
header_image = models.ImageField(null=True, blank=True, upload_to="images/news/header/")
body = RichTextUploadingField()
date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(
AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
category = models.ManyToManyField(Category, default='cryptocurrency', related_name='category')
like_news = models.ManyToManyField(AUTH_USER_MODEL, blank=True, related_name='the_news')
unlike_news = models.ManyToManyField(AUTH_USER_MODEL, blank=True, related_name='the_news_unlike')
def total_likes(self):
return self.like_news.count()
def total_unlikes(self):
return self.unlike_news.count()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("news_detail", args=[str(self.id)])
Which part of the code is wrong that shows the username like this?
You need to return self.username, not self.USERNAME_FIELD:
class CustomUser(AbstractBaseUser, PermissionsMixin):
# …
USERNAME_FIELD = 'username'
def __str__(self):
return self.username
or if you want to return the attribute with the USERNAME_FIELD, you can use the getattr(…) function [Python-doc]:
class CustomUser(AbstractBaseUser, PermissionsMixin):
# …
USERNAME_FIELD = 'username'
def __str__(self):
return getattr(self, self.USERNAME_FIELD)

Using ForeignKey of Django CustomUser giving attribute error

Not using Djnago Default user model. Have created a Custom user model named CustomUser
class CustomUser(AbstractBaseUser):
GENDER_CHOICE = (
('MALE', 'MALE'),
('FEMALE', 'FEMALE'),
)
BLOOD_GROUP_CHOICE = (
('A+', 'A+'),
('B+', 'B+'),
('O+', 'O+'),
('AB+', 'AB+'),
('A-', 'A-'),
('B-', 'B-'),
('O-', 'O-'),
('AB-', 'AB-'),
)
RELIGION_CHOICE = (
('ISLAM', 'ISLAM'),
('HINDU', 'HINDU'),
('CHRISTIANITY', 'CHRISTIANITY'),
('OTHER', 'OTHER'),
)
email = models.EmailField(max_length=60, unique=True, verbose_name='Email')
first_name = models.CharField(max_length=30, verbose_name='First Name')
last_name = models.CharField(max_length=30, verbose_name='Last Name')
gender = models.CharField(_("Employee Gender"),
max_length=6, choices=GENDER_CHOICE, null=True, blank=True)
blood_group = models.CharField(
_("Employee Blood Group"), max_length=3, choices=BLOOD_GROUP_CHOICE, null=True, blank=True)
birth_of_date = models.DateField(
_("Employee Birth Date"), auto_now=False, auto_now_add=False, null=True, blank=True)
#address = models.CharField(_("Employee Address"), max_length=500, null=True, blank=True)
address = models.CharField(_("Employee Address"), max_length=500, null=True, blank=True)
phone_number = PhoneNumberField(null=True, blank=True)
profile_pic = models.ImageField(_("Employee Profile Picture"), upload_to='profile_pic',
height_field=None, width_field=None, max_length=None, null=True, blank=True)
religion = models.CharField(
_("Employee Religion"), max_length=15, choices=RELIGION_CHOICE, null=True, blank=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ('first_name', 'last_name')
objects = CustomUserManager()
def __str__(self):
return self.email
def get_short_name(self):
return self.first_name
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return self.is_admin
class Meta:
verbose_name_plural = "Shunno ek Users"
Here is my CumstomUser models' CustomUsermanager
class CustomUserManager(BaseUserManager):
def create_user(self, email, first_name, last_name, password=None):
if not email:
raise ValueError('You must have an email')
email = email.lower()
first_name = first_name.title()
last_name = last_name.title()
user = self.model(
email = self.normalize_email(email),
first_name = first_name,
last_name = last_name
)
#user.password = password
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, first_name, last_name, password=None):
user = self.create_user(
email = email,
first_name = first_name,
last_name = last_name,
password = password
)
user.is_admin = True
user.is_staff = True
user.save(using=self._db)
return user
This is a model of saving users Quiz answers.
class UserAns(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quiz_user')
quizcat = models.ForeignKey(Category, on_delete=models.CASCADE)
totalq = models.DecimalField(max_digits=5,decimal_places=2)
correcta = models.DecimalField(max_digits=5,decimal_places=2)
def __str__(self):
return self.User.first_name
It is view part where i want to save the data of user answer.
def quizpage(request, slug):
if request.method == 'POST':
# totalquestion
solve = 0
for question in range(1,cat.totalq+1):
entered_answer_questionpk = request.POST.get(str(question))
ans = entered_answer_questionpk[:1]
qpk = int(entered_answer_questionpk[1:])
actualans = Question.objects.get(pk=qpk).correct_answer
if ans == actualans:
solve = solve + 1
# print(user)
usersans = UserAns(totalq=cat.totalq, correcta=solve)
usersans.quizcat = cat
print(request.user)
usersans.user = request.user
usersans.save()
return render(request, 'quiz/quizpage.html',{'questions': questions })
after saving this value in the database, when I click the table name it gives this error:
Django Version: 3.1.3
Exception Type: AttributeError
Exception Value:
'UserAns' object has no attribute 'User'
I can't understand where is my problem.
Your string method is referencing self.User and not self.user.
def __str__(self):
return self.user.first_name
Previous answer:
You should also look through your view that's rendering the page and protect any parts that access userans.user via if hasattr(userans, 'user'): or if userans.user_id:.
Another thing you can do is clean up your data. Your post view looks to be about right. But that page is failing because you have instances that still have the user property with a value of None.Open up a shell manage.py shell, import your UserAns model and see if you have any instances without a user. If you do, determine which user(s) they should map to or delete them.
UserAns.objects.filter(user__isnull=True)

Change Passwod API using Django Custom user model and serializer

I have a Django application hwere I have extended the User model and created a custom user model for registration/login, now I want to implement a Change Password API which will be used in Android/IOS app development. I would get parameters as:
user_id, old_password, new_password
Using these paramters and custom user model and serializer is there any way I could achieve this.
I have tried a sample example for this, but it failed.
Custom Model:
class User(AbstractBaseUser, PermissionsMixin):
objects = UserManager()
name = models.CharField(max_length=100, blank=True, null=True)
email = models.EmailField(unique=True)
created_at = models.DateField(blank=True, null=True, auto_now=True)
phone_no = models.CharField(max_length=14, blank=True, null=True)
user_android_id = models.CharField(max_length=255, blank=True, null=True)
user_fcm_token = models.CharField(max_length=255, blank=True, null=True)
user_social_flag = models.IntegerField(blank=True, null=True)
user_fb_id = models.CharField(max_length=255, blank=True, null=True)
user_android_app_version = models.CharField(max_length=25, blank=True, null=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
USERNAME_FIELD = 'email'
def __str__(self):
return self.email
User Manager:
class UserManager(BaseUserManager):
use_in_migrations = True
def create_user(self, email, name, phone_no, created_at, user_android_id, user_fcm_token,
user_social_flag, user_fb_id, user_android_app_version, password=None):
cache.clear()
user = self.model(
email=self.normalize_email(email),
phone_no=phone_no,
created_at=created_at,
user_android_id=user_android_id,
user_fcm_token=user_fcm_token,
user_social_flag=user_social_flag,
user_fb_id=user_fb_id,
user_android_app_version=user_android_app_version,
name=name,
)
user.is_admin = False
user.is_staff = True
user.is_superuser = False
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, email, name, created_at, phone_no, user_android_id, user_fcm_token,
user_social_flag, user_fb_id, user_android_app_version, password):
cache.clear()
user = self.create_user(
email,
# password=password,
created_at=created_at,
phone_no=phone_no,
user_android_id=user_android_id,
user_fcm_token=user_fcm_token,
user_social_flag=user_social_flag,
user_fb_id=user_fb_id,
user_android_app_version=user_android_app_version,
name=name,
)
user.set_password(password)
user.is_staff = True
user.is_admin = False
user.is_superuser = False
user.save(using=self._db)
return user
def create_superuser(self, email, password):
cache.clear()
user = self.model(
email=self.normalize_email(email),
# password=password,
# phone_no=phone_no,
# created_at=created_at,
# user_android_id=user_android_id,
# user_fcm_token=user_fcm_token,
# user_social_flag=user_social_flag,
# user_fb_id=user_fb_id,
# user_android_app_version=user_android_app_version,
# name=name,
)
user.set_password(password)
user.is_admin = True
user.is_staff = False
user.is_superuser = True
user.save(using=self._db)
return user
Custom User Serializer:
class CustomRegisterSerializer(RegisterSerializer):
email = serializers.EmailField(required=False)
password1 = serializers.CharField(required=False, allow_null=True, allow_blank=True)
name = serializers.CharField(required=False, allow_null=True, allow_blank=True)
phone_no = serializers.CharField(required=False, allow_null=True, allow_blank=True)
user_android_id = serializers.CharField(required=False, allow_null=True, allow_blank=True)
user_fcm_token = serializers.CharField(required=False, allow_null=True, allow_blank=True)
user_social_flag = serializers.IntegerField(required=False, allow_null=True)
user_fb_id = serializers.CharField(required=False, allow_null=True, allow_blank=True)
user_android_app_version = serializers.CharField(required=False, allow_null=True, allow_blank=True)
# created_at = serializers.DateField(format="%Y-%m-%d", input_formats=['%Y-%m-%d', 'iso-8601'])
class Meta:
model = User
fields = ('email', 'password', 'name', 'phone_no', 'user_android_id', 'user_fcm_token',
'user_social_flag', 'user_fb_id', 'user_android_app_version')
def get_cleaned_data(self):
super(CustomRegisterSerializer, self).get_cleaned_data()
return {
'password1': self.validated_data.get('password1', ''),
'email': self.validated_data.get('email', ''),
'phone_no': self.validated_data.get('phone_no', ''),
'name': self.validated_data.get('name', ''),
'user_android_id': self.validated_data.get('user_android_id', ''),
'user_fcm_token': self.validated_data.get('user_fcm_token', ''),
'user_social_flag': self.validated_data.get('user_social_flag', ''),
'user_fb_id': self.validated_data.get('user_fb_id', ''),
'user_android_app_version': self.validated_data.get('user_android_app_version', ''),
}
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
return user
ChangePassword API :
class CustomChangePasswordView(APIView):
"""
User Change Password API
"""
def post(self, request):
data = request.data
u_id = data.get('user_id')
old_password = data.get('user_old_password')
new_password = data.get('user_new_password')
user = User.objects.get(id=u_id)
if user.password != old_password:
return Response({"msg":"Invalid Old Password"}, status=status.HTTP_200_OK)
else:
user.set_password(new_password)
return Response({"msg":"Change successfull!"}, status=status.HTTP_201_CREATED)
Error Response I get:
{
"msg": "Invalid Old Password"
}
What am I missing?
Is there another better way for this?
Update in the CustomChangePasswordView code like this:
if user.check_password(old_password):
user.set_password(new_password)
user.save()
return Response({"msg":"Change successfull!"}, status=status.HTTP_201_CREATED)
else:
return Response({"msg":"Invalid Old Password"}, status=status.HTTP_200_OK)
You can check the documentation on check password in here.