1

我是 django rest 框架的新手。我创建了两个注册模型——用户模型和医生模型。现在尝试创建 lopin API。如何在 1 个 API 下实现两种不同的模型。请建议我在同一登录 API 中验证用户和医生的登录凭据。

模型.py

class User(AbstractUser):
    username = models.CharField(_('username'), max_length=100)
    email = models.EmailField(_('email address'),max_length=100,unique=True)
    is_doctor = models.BooleanField(_('doctor status'),default=False)
    is_admin = models.BooleanField(_('admin status'),default=False)
    phone = models.CharField(_('phone number'), max_length=50)
    address = models.TextField(_('address'))
    dob = models.CharField(_('date_of_birth'), max_length=20)
    education = models.CharField(_('education'), max_length=100, default='', editable=True)
    work_status = models.CharField(_('work status'), max_length=100, default='', editable=True)
    gender = models.CharField(_('gender'), max_length=10)
    city = models.CharField(_('city'), max_length=50)
    role = models.CharField(_('role'), max_length=10, default='user', editable=False)


    class Meta(AbstractUser.Meta):
        swappable = 'AUTH_USER_MODEL'

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    def get_email(self):
        return f'{self.email}'

    def __str__(self):
        return f'{self.email}'

    def create_superuser(self, username, email, password):
        """
        Creates and saves a superuser with the given email and password.
        """
        # user = self.CreateUser(username, email,
        #     password=password,
        # )
        user = self.model(
            email=self.normalize_email(email)
        )
        user.username = username
        user.set_password(password)
        user.is_admin = True
        user.save(using=self._db)
        return user

class Doctor(models.Model):
    doctor_name = models.CharField(max_length=20)
    doctor_reg_id = models.CharField(max_length=100)
    qualification = models.CharField(max_length=200)
    hospital_address = models.TextField()
    phone = models.CharField(max_length=200)
    email = models.EmailField(max_length=100, unique=True)
    password = models.CharField(max_length=100)
    specialization = models.CharField(max_length=100, default='', editable=True)
    about_me = models.TextField()
    role = models.CharField(max_length=10, default='doctor', editable=False)

序列化程序.py

class UserRegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id','username','email','password', 'phone', 'address', 'dob', 'education', 
                     'work_status', 'gender', 'city', 'role']
        extra_kwargs = {'password':{'write_only':True}}

        def create(self, validated_data):
            user = User.objects.create_user(validated_data['username'], validated_data['email'],
                                            validated_data['password'])

            return user

视图.py

class Register_Users(APIView):

    permission_classes = [AllowAny]
    serializer_class = UserRegisterSerializer
    def post(self, request):
        data = {}
        serializer = UserRegisterSerializer(data=request.data)
        if serializer.is_valid():
            account = serializer.save()
            account.save()
            token = Token.objects.get_or_create(user=account)[0].key
            data['message'] = "Successful Registration"
            # data['email'] = account.email
            # data['username'] = account.username
            # data['token'] = token
            return Response(serializer.data)
        else:
            return Response(serializer.errors)

class Doctor_Registration(APIView):

    permission_classes = [AllowAny]
    serializer_class = DoctorSerializer
    def post(self, request):
        data = {}
        serializer = DoctorSerializer(data=request.data)
        if serializer.is_valid():
            account = serializer.save()
            account.save()
            token = Token.objects.get_or_create(user=account)[0].key
            # data['email'] = account.email
            # data['username'] = account.username
            # data['token'] = token
            return Response(serializer.data)
        else:
            return Response(serializer.errors)


class LoginUser(APIView):

    permission_classes = [AllowAny]
    # queryset = User.objects.all()
    serializer_class = UserLoginSerializer

    def post(self, request):
        data = {}
        serializer = UserLoginSerializer(data=request.data)
        if serializer.is_valid():
            try:

                Account = User.objects.get(email=serializer.validated_data['email'], 
                                 password=serializer.validated_data['password'])
                token = Token.objects.get_or_create(user=Account)[0].key
                login(request, Account)
                data["message"] = "Login Successful"
                data["token"] = token
                data["username"] = request.user.username
                data["role"] = request.user.role
                return Response(data)
            except:
                return Response(serializer.errors)
4

0 回答 0