Reputation: 29
I wanted to use email instead of username to login the user, so I obtained below code from the django documentation from custom authorization section.
class UserManager(BaseUserManager):
def create_user(self, email, name, password=None, password2=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('User must have an Email Address')
user = self.model(
email=self.normalize_email(email),
name = name
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, name, password=None):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(
email,
name=name,
password=password
)
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,
)
name = models.CharField(max_length=255)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
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
I have used custom user manager and added email field and name field. Name is required and authorization will be done using email of the user. I was able to create super user and login successfully. I was also able to register the user using REST endpoint. I want to try to login the user and view the profile. I was able to successfully login user and get access & refresh token using Simple JWT. But when I try to hit profile endipoint I get
"Invalid data. Expected a dictionary, but got User." Error
My view is as follows, I am using UserRenderer to get response in the required format, this works correctly for user registration and login endpoints and I dont think thats the issue here.:
@api_view(["GET"])
@renderer_classes([UserRenderer])
@permission_classes([IsAuthenticated])
def user_profile(request):
print("DATA", request.user)
serializer = UserProfileSerializer(data=request.user)
if serializer.is_valid():
return Response({"data":serializer.data}, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Here print statement give me the email of the user trying to access the endpoint, I think it obtains it from the token passed. And serializer I used is
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'name', 'email']
I am passing access token as Bearer token in header section of the endpoint
Upvotes: 0
Views: 296
Reputation: 1153
You are passing request.user
inside serializer data, you should do:
serializer = UserProfileSerializer(data=request.data)
Upvotes: 0