Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

django - How to Create custom permission classes?

models:

class DoctorProfile(AbstractBaseUser, PermissionsMixin):
    id=models.AutoField(primary_key=True)
    name = models.CharField(_('name'), max_length=50, blank=True)
    mobile = models.CharField(_('mobile'), unique=True, max_length=10, blank=False)
    # mobile=  models.CharField(primary_key=True , max_length=10, validators=[RegexValidator(r'^d{1,10}$')])
    # mobile= models.IntegerField(validators=[MinValueValidator(10),MaxValueValidator(10)])
    email = models.EmailField(_('email address'), blank=True)
    password = models.CharField(_('password'),max_length=25,blank=False)
    date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
    is_verified=models.BooleanField(default=False)
    is_active = models.BooleanField(_('active'), default=False)
    is_doctor = models.BooleanField(_('active'), default=False)
    otp = models.IntegerField(null=True, blank=True)
    dob=models.DateField()
    GENDER_CHOICES = (
    ('M', 'Male'),
    ('F', 'Female'),
  )
   gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

How to Create custom permission for creating tasks ? eg:

class ClinicRegistrationView(generics.ListCreateAPIView):
     serializer_class = ClinicSerializer
     queryset = Doctor_clinic.objects.all()
     permission_classes = (permissions.IsAuthenticated,)#token user can create

How to give is_doctor permission ,only create task ??


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
from rest_framework.permissions import BasePermission


class IsDoctorPermission(BasePermission):
    """
    Check if user is a doctor.
    """

    message = "The user is not a doctor."

    def has_permission(self, request, view):
        return request.user.is_doctor

and add this permission to the view

class ClinicRegistrationView(generics.ListCreateAPIView):
     serializer_class = ClinicSerializer
     queryset = Doctor_clinic.objects.all()
     permission_classes = (permissions.IsAuthenticated, IsDoctorPermission)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...