florimondmanca / djangorestframework-api-key

🔐 API key permissions for Django REST Framework
https://florimondmanca.github.io/djangorestframework-api-key/
MIT License
678 stars 104 forks source link

Need sample guide for POST method for APIview in serializer #194

Closed Mr-Apisit closed 2 years ago

Mr-Apisit commented 2 years ago

About AbstractAPIKey, In admin sit on organization_key foreignKey they can select organization field and generate prefix as well

But in serializer APIView POST on request json body the prefix not generate them self they save "" to model

class OrganizationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Organization
        fields = ["id", "name", "active"]

class OrganizationAPIKeySerializer(serializers.ModelSerializer):
    organization = serializers.PrimaryKeyRelatedField(many=False, queryset=Organization.objects.all())

    class Meta:
        model = OrganizationAPIKey
        fields =  ['id',"name","organization","prefix","hashed_key","revoked","expiry_date"]
        read_only_fields = ["created"]

class Createkey(APIView):
    serializer_class = OrganizationAPIKeySerializer
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        events = self.serializer_class(data = request.data)
        if events.is_valid():
            events.save()
            contents = {"status":"complete","data":events.data}
            return Response(contents)
        contents = {"status":"error","data":[],"errors":events.errors}
    return Response(contents)