Júnior Carvalho
Júnior Carvalho

Reputation: 11

Django Rest Framework - How to call method model

I need to call a method from a template. I have the following codes:

models.py

class Operation(Base):
    ...
    hash_code = models.UUIDField(default=uuid4)
    ...

    def open_operation(self, user):
       ...
       pass

views.py

class OperationOpenView(APIView):
"""
patch:
"""

    filter_backends = (filters.DjangoFilterBackend,)
    filter_class = OperationOpenFilter

    def patch(self, request, id):
        user = request.user
        operation = Operation.objects.get(pk=id)
        serializer = OperationOpenSerializer(operation, 
                     data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            serializer.instance.open_operation(user)
            return Response(data={'operation': operation, 'user': user}, status=status.HTTP_200_OK)
        else:
            return Response(code=400, status=status.HTTP_400_BAD_REQUEST)

serializers.py

class OperationOpenSerializer(serializers.ModelSerializer):
    class Meta:
        model = Operation
        fields = ('id', )
        depth = 1

filters.py

class OperationOpenFilter(filters.FilterSet):

id = filters.NumberFilter(
    label='id',
    required=True,
    help_text='ID'
)

class Meta:
    model = Operation
    fields = ['id',]

urls.py

path(r'operations/open', views.OperationOpenView.as_view()),

tests.py

@pytest.mark.django_db
def test_view(client_api_logged):
    response = client_api_logged.patch('/api/operations/open', kwargs= 
    {'id': '1'})
    assert response.status_code == 200

I'm not getting it to work, getting the error:

"TypeError at /api/operations/open patch() missing 1 required positional argument: 'id'"

any light at the end of the tunnel?

thank you all

Upvotes: 1

Views: 1628

Answers (1)

ruddra
ruddra

Reputation: 51978

You need to fix your url:

path(r'operations/open/<int:id>/', views.OperationOpenView.as_view()),

And in tests.py:

response = client_api_logged.patch('/api/operations/open/1/', kwargs={'id':1})

Explanation:

The patch method takes 3 parameters (self, request, id). Python(object reference) provides 'self', Django provides 'request' and the URL needs to provide the 'id'. The URL mapping in the post didn't include an 'id' so Django complains about a missing parameter. from comment of Ben

Upvotes: 1

Related Questions