Hello everyone, I’m trying to make it when someone creates a User model an account gets created and you get the account primary key and use it in the model.
models.py
class User(models.Model):
accountID = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
first_name= models.CharField(max_length=20 , null = False)
last_name= models.CharField(max_length=20, null = False)
phone = models.CharField(null=False,max_length=100)
email = models.EmailField(verbose_name='user email address', max_length=100, unique=True)
clinicID= models.ForeignKey(Clinic,on_delete=models.CASCADE , null=False)
roleID=models.ForeignKey(Role,on_delete=models.CASCADE,null= False, default=1)
def __str__(self):
return self.first_name+" "+self.last_name
class UserManager(UserManager):
def create_user(self, email, password=None):
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, email, password):
user = self.create_user(email,password=password)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(
email,
password=password,
)
user.staff = True
user.admin = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
objects = UserManager()
email = models.EmailField(verbose_name='user email address', max_length=100, unique=True)
username=models.CharField(max_length=50,default="")
roleID=models.ForeignKey(Role,on_delete=models.CASCADE,null= False,default=1)
is_active = models.BooleanField(default=True,null=False)
is_staff = models.BooleanField(default=False,null=False)
is_admin = models.BooleanField(default=False,null=False)
is_superuser=models.BooleanField(default=False,null=False)
password=models.CharField(max_length=100,)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def get_full_name(self):
# users identification is by email
return self.email
def get_user_short_name(self):
# user identification is by email
return self.email
def __str__(self):
return (str(self.pk)+" "+self.email)
def has_perm(self, perm, obj=None):
# return true if user has the necessary permissions
return True
def has_module_perms(self, app_label):
# return true if user is granted the permission to view 'app_label'
return True
serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model= User
fields='__all__'
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields =(
'id',
'email',
'username',
'password',
'roleID',
)
def validate(self, args):
email = args.get('email', None)
if Account.objects.filter(email=email).exists():
raise serializers.ValidationError({'email': ('email already exists')})
return super().validate(args)
def create(self, validated_data):
return Account.objects.create(**validated_data)
views.py
class RegistrationAPIView(generics.GenericAPIView):
serializer_class = AccountSerializer
def post(self, request):
data = request.data
if(request.POST['password']==""):
request.data._mutable = True
request.POST['password']=UserManager().make_random_password()
data._mutable = False
if(request.POST['username']==""):
request.data._mutable = True
request.POST['username']=request.POST['email'].split('@')[0]
data._mutable = False
serializer = AccountSerializer(data = request.data)
if(serializer.is_valid()):
#message="Welcome to , your password is :"+self.request.data['password']+"\n Hope to see you at work"
#send_mail(
# 'Welcome to ',
# message,
# settings.EMAIL_HOST_USER ,
# [self.request.data['email']],
# fail_silently=False
# )
password = make_password(request.data['password'])
serializer.save(password=password)
return Response({
"RequestId": str(uuid.uuid4()),
"Message": "User created successfully",
"Account": serializer.data}, status=status.HTTP_201_CREATED
)
else:
return Response({'ERROR': ('email may already exists')},status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class userCreateList(APIView):
def get(self,request):
queryset = User.objects.all()
serializer_class = UserSerializer(queryset, many=True)
return Response(serializer_class.data)
def post(self, request, format=None):
#the part that I'm getting wrong
userrequest=HttpRequest()
usercontext={'email':request.data["email"],'roleID':request.data["roleID"],'password':'','username':''}
userrequest.method='POST'
userrequest.data=usercontext
response =RegistrationAPIView.as_view()(userrequest)
print(response)
#################################
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
```
If anyone has any how to make it work it would be appreciated :D