1

I need to allow a certain user, who is specified in the model, to modify a few of the model's fields. I know I need to create a permission class, which will control the whole process, but I have no idea how to do that. Here's the code sample:

class Task(models.Model):
   creator = models.ForeignKey('auth.User', related_name='created_tasks', on_delete=models.CASCADE)
   target = models.ForeignKey(User, related_name='assigned_tasks', on_delete=models.CASCADE)
   title = models.CharField(max_length=100)
   description = models.TextField()
   created = models.DateTimeField(auto_now_add=True)
   deadline = models.DateTimeField()
   priority = models.CharField(max_length=50, choices=PRIORITY_CHOICES, default='NORMAL')
   progress = models.CharField(max_length=50, choices=PROGRESS_CHOICES, default='ASSIGNED')
   is_finished = models.BooleanField(default=False)

So I want to allow the target, to modify only progress and is_finished fields.

I am using DjangoRestFramework, not sure if that will help. Should I create a method, which will check if user == target, and ignore all the other changes or is it possible to create a permission which will do that.

Michal G
  • 45
  • 5

2 Answers2

0

You can use groups, assign certain permissions on that group and put your target user in your group, just need to go to admin site to setup the groups. Hope this help you.

zhiqiang huang
  • 353
  • 2
  • 13
  • Thank you for the answer The problem I have is the fact, all of the users can create a task, and specify a person, who is responsible for finishing the task (a target). If I am correct, I cannot assign group's permissions to a certain task. – Michal G Nov 16 '17 at 20:09
  • Create,edit,delete those are different permissions, you can make everyone has create permission, but make only certain goup has edit and delete permisions. – zhiqiang huang Nov 16 '17 at 20:27
0

serializers.py

from rest_framework import serializers
class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        exclude = ()

    def update(self, instance, validated_data):
        if self.context['request'].user == specified_user:
            setattr(instance, 'progress', validated_data.get('progress', None))
            setattr(instance, 'is_finished', validated_data.get('is_finished', None))
            instance.save()
            return instance
        return super(TaskSerializer, self).update(instance, validated_data)
origamic
  • 1,076
  • 8
  • 18