0

i have a problem with my viewset in DRF:

def get_queryset(self):
    """
    :return: filtered queryset based on request query_param

    """
    # todo#amedeo: improve the readability code
    qs = super(ChecklistViewSet, self).get_queryset()
    _pk = self.kwargs['pk']

    if self.request.method == 'PUT':
        instance = qs.filter(pk=int(_pk)).first()
        # pass in the instance we want to update
        serializer = ChecklistSerializer(instance, self.request.data)

        # validate and update
        if serializer.is_valid():
            serializer.save()
            serializer_dict = serializer.data
            serializer_dict["message"] = "Checklist updated successfully."
            return response.Response(serializer_dict, status=status.HTTP_200_OK)

        else:
            return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

in my code the objetc was saved, but the response give an error that say:

AttributeError: 'Response' object has no attribute 'model'

My serializer is:

class ChecklistSerializer(serializers.ModelSerializer):

class Meta:
    model = Checklist
    fields = ('id', 'approved_by', 'role', 'hardship_classification',
              'total_capacity', 'capacity_for_residents', 'checklist_type',
              'state', 'pdf', 'submitting_afp', 'disabled', 'location')

i call by client PUT method passing json:

{
"approved_by": "Test",
"role": "test_role_4",
"hardship_classification": "test_6",
"total_capacity": "50",
"capacity_for_residents": "350",
"checklist_type": "permanent",
"state": "qcl_draft",
"pdf": null,
"submitting_afp": 3999,
"disabled": false,
"location": 97
}

but i receved that Error. The model was saved but Response give me the Error

Internal Server Error: /api/v1/checklists/3/ Traceback (most recent call last): File "/home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/rest_framework/viewsets.py", line 116, in view return self.dispatch(request, *args, **kwargs) File "/home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "/home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/rest_framework/views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "/home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/rest_framework/views.py", line 483, in dispatch self.initial(request, *args, **kwargs) File "/home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/rest_framework/views.py", line 401, in initial self.check_permissions(request) File "/home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/rest_framework/views.py", line 334, in check_permissions if not permission.has_permission(request, self): File "/home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/rest_framework/permissions.py", line 206, in has_permission perms = self.get_required_permissions(request.method, queryset.model) AttributeError: 'Response' object has no attribute 'model' "PUT /api/v1/checklists/3/ HTTP/1.1" 500 42934

enter code here

4
  • can you post class ChecklistSerializer Commented Dec 24, 2018 at 8:49
  • class ChecklistSerializer(serializers.ModelSerializer): class Meta: model = Checklist depth = 1 fields = ('id', 'approved_by', 'role', 'hardship_classification', 'total_capacity', 'capacity_for_residents', 'checklist_type', 'state', 'pdf', 'submitting_afp', 'disabled', 'location') Commented Dec 24, 2018 at 8:53
  • @AmedeoDiFilippo can you post the full traceback Commented Dec 24, 2018 at 9:23
  • @WillKeeling perms = self.get_required_permissions(request.method, queryset.model) AttributeError: 'Response' object has no attribute 'model' "PUT /api/v1/checklists/3/ HTTP/1.1" 500 42934 Commented Dec 24, 2018 at 9:36

2 Answers 2

2

the get_queryset method should return the queryset not Response and the update action should be overrided in the put method. Read here class-based-views and filtering for more details. May be you need to remove the get_queryset overriding and just add the put method somethig like this:

def put(self, request, pk, format=None):
    instance = self.get_object(pk)
    # pass in the instance we want to update
    serializer = ChecklistSerializer(instance, self.request.data)

    # validate and update
    if serializer.is_valid():
        serializer.save()
        serializer_dict = serializer.data
        serializer_dict["message"] = "Checklist updated successfully."
        return response.Response(serializer_dict, status=status.HTTP_200_OK)

    else:
        return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Sign up to request clarification or add additional context in comments.

3 Comments

i'm using Django 1.11 on my project
it doesn't matter django version. why you write it?
Sorry, i'm new in Django and python. For that method i define the correct url in my urls file .*py? My urls.py is this: router.register(r'checklists', checklist.ChecklistViewSet, base_name='checklists') urlpatterns = ( url(r'^', include(router.urls)), )
0

you can do this

from django.shortcuts import get_objects_or_404

class YourAPIView(ModelViewSet):
   def put(self, request, pk):
       instance = get_objects_or_404(YourModel, pk=pk)
       serializer = ChecklistSerializer(instance, self.request.data)

# validate and update
       if serializer.is_valid():
           serializer.save()
           serializer_dict = serializer.data
           serializer_dict["message"] = "Checklist updated successfully."
           return response.Response(serializer_dict, status=status.HTTP_200_OK)
       return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.