Reputation: 321
I am writing a REST API to create Group and assign permissions to that group.
Issue: How to create POST Method so that I can create a group having those permissions.
Here is Snippet of code so far I have came
Groupserializer
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ('name','permissions')
Views
class UsersGroupCreateView(APIView):
permission_classes = [IsAdminUser]
def post(self , request , *args, **kwargs):
serializer = GroupSerializer(data = request.data)
if serializer.is_valid():
data = serializer.validated_data
group = Group.objects.create(name = data.get('name'), permissions =
data.get('permissions'))
return Response({"status":"Group Created"},status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST
class GetPerm(APIView):
def get(self, request, *args, **kwargs):
permissions = serializers.serialize('json', Permission.objects.all())
return Response(permissions)
permissions from GetPerm() has following data:
"[{"model": "auth.permission", "pk": 1, "fields": {"name": "Can add log entry", "content_type": 1, "codename": "add_logentry"}}, {"model": "auth.permission", "pk": 2, "fields": {"name": "Can change log entry", "content_type": 1, "codename": "change_logentry"}}, {"model": "auth.permission", "pk": 3, "fields": {"name": "Can delete log entry", "content_type": 1, "codename": "delete_logentry"}}, {"model": "auth.permission", "pk": 4, "fields": {"name": "Can view log entry", "content_type": 1, "codename": "view_logentry"}}]"
Sorry , if I am not being much clear Any help would be appreciated !!
Upvotes: 1
Views: 2810
Reputation: 321
I figured it out, and it's something like this.
group = Group.objects.create(name = data.get('name'))
try:
permissions = request.data.get('permissions')
for permission_index in permissions:
permission=Permission.objects.get(id=permission_index)
group.permissions.add(permission)
except Exception as e:
print("Error in creating")
return Response({"status":"Group Created"},status=status.HTTP_201_CREATED)
also thanks to @afonso.
Upvotes: 0
Reputation: 8077
As the error states, you cannot directly assign ManyToMany
relationships when first creating the object. You need to do it manually after :
# ...
if serializer.is_valid():
data = serializer.validated_data
group = Group.objects.create(name = data.get('name'))
[group.permissions.add(p) for p in data.get('permissions')]
return Response({"status":"Group Created"},status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# ...
Upvotes: 2