Home > Software design >  How to disallow to change "status" for simple user and keep it for admin and support(super
How to disallow to change "status" for simple user and keep it for admin and support(super

Time:09-22

The simple user must either not see the status button or it must be grayed out for selection. Admin(user.is_staff) and Support(user.is_superuser) should see the field and be able to change it.

Now user can change the status of ticket in Update view.

enter image description here

My serializer:

class TicketSerializerUpdate(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    status = Status.objects.all()

    class Meta:
        model = Ticket
        fields = "__all__"

My models Ticket and Status:

class Status(models.Model):
    status = models.CharField(max_length=150)
    desc_status = models.TextField()

    def __str__(self):
        return self.status


class Ticket(models.Model):
    title = models.CharField(max_length=150)
    text = models.TextField()
    status = models.ForeignKey(Status, on_delete=models.PROTECT, default=2)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    time_create = models.DateTimeField(auto_now_add=True)
    time_update = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

File permissions now haven't anything for solve the problem and I haven't any idea. I think it is simple problem, if you need more info you can request me)

CodePudding user response:

You can use different Serializers for different users in your view using get_serializer_class():

class SimpleUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ticket
        fields = "__all__"
        read_only_fields =  ('status',)

class AdminUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ticket
        fields = "__all__"

class ExampleView(viewsets.ModelViewSet):    
    ...
    def get_serializer_class(self):
        if self.request.user.is_admin:
            return AdminUserSerializer
        return SimpleUserSerializer
  • Related