this is my models.py file :
from django.db import models
from django.contrib.auth.models import AbstractUser
from .manager import CustomUserManager
STATE_CHOICES = (
('Odisha', 'Odisha'),
('Karnataka', 'Karnataka')
)
ROLES = (
('admin', 'admin'),
('customer', 'customer'),
('seller', 'seller'),
)
class User_role(models.Model):
role = models.CharField(max_length=50, blank=True)
class User_Profile(AbstractUser):
email = models.EmailField(unique=True)
username = models.CharField(max_length=100)
password = models.CharField(max_length=50)
role = models.ForeignKey(User_role, on_delete=models.CASCADE)
def __str__(self):
return self.email
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = CustomUserManager()
class Product(models.Model):
title = models.CharField(max_length=100)
selling_price = models.FloatField()
discount_price = models.FloatField()
description = models.TextField()
productImg = models.ImageField(upload_to="productImages")
class Cart(models.Model):
user_profile = models.ForeignKey(User_Profile, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField(default=1)
class Order_Placed(models.Model):
user_profile = models.ForeignKey(User_Profile, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField(default=1)
order_date = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=50)
this is my managers.py file :
from django.contrib.auth.models import BaseUserManager
class CustomUserManager(BaseUserManager):
def create_user(self, email, username, password=None, role=None, **extra_fields):
if not email:
raise ValueError('The Email field must be set')
email = self.normalize_email(email)
user = self.model(email=email, username=username, role=role, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password=None, role=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
# Assign a default role for superusers
if role is None:
# role = 'admin'
from .models import User_role
role = User_role.objects.get(role='admin')
return self.create_user(email, username, password, role, **extra_fields)
This is my serializers.py file :
from django.contrib.auth.models import User
from rest_framework import serializers, validators
from .models import *
from django.contrib.auth.hashers import make_password
class RegisterSerializers(serializers.ModelSerializer):
class Meta:
model = User_Profile
fields = ('username','email','password','role')
extra_kwargs = {
"password": {"write_only": True},
"email": {
"required": True,
"validators": [
validators.UniqueValidator(
User_Profile.objects.all(), "A user with that email already exists"
)
]
}
}
def create(self, validated_data):
username = validated_data.get("username")
email = validated_data.get("email")
# Hashing the Password
password = validated_data.get("password")
# Hash the password using Django's password hasher
hashed_password = make_password(password)
# Update the validated_data with the hashed password
validated_data['password'] = hashed_password
password = hashed_password
role = validated_data.get("role")
# Check if the role is a string and convert it to an integer if needed
if isinstance(role, str):
role = int(role)
user = User_Profile.objects.create(
username= username,
email= email,
password= password,
role = role
)
return user
This is my views.py file :
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.authtoken.serializers import AuthTokenSerializer
from knox.auth import AuthToken
from .serializers import RegisterSerializers
# user login API
@api_view(['POST'])
def login_api(request):
serializer = AuthTokenSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
_, token = AuthToken.objects.create(user)
return Response({
'user_info': {
'id': user.id,
'username': user.username,
'email': user.email
},
'token': token
})
# get user data API
@api_view(['GET'])
def get_user_data(request):
user = request.user
if user.is_authenticated:
return Response({
'user_info': {
'id': user.id,
'username': user.username,
'email': user.email
},
})
return Response({'error':'not authenticated'},status=400)
# register user API
@api_view(['POST'])
def register_api(request):
serializer = RegisterSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
_, token = AuthToken.objects.create(user)
return Response({
'user_info': {
'id': user.id,
'username': user.username,
'email': user.email
},
'token': token
})
On postman app registration and logout is working fine but login is not working.
The passwords are stored in hashed format and also after registering tokens are saved in admin panel.
Please help me.