Django Rest Framework PUT request returns 500, but updates data









up vote
2
down vote

favorite












I'm fairly new to Django REST framework and I've tried to write an API for my mobile application. I'm facing an issue where a PUT request works fine (updates data) apart from the fact it returns response 500 (Internal Server Error). Some guidance towards resolving this would be much appreciated.



views.py:



@csrf_exempt
def category_instance(request, pk):
"""
Returns Category instance
"""
try:
cat = Category.objects.get(pk=pk)
except Category.DoesNotExist:
return HttpResponse("Error: category does not exist", status=404)

if request.method == 'GET':
serializer = CategorySerializer(cat, many=False)
return JsonResponse(serializer.data, safe=False)

elif request.method == 'PUT':
serializer = CategorySerializer(cat, data=request.data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, 200)
return JsonResponse(serializer.errors, status=400)

elif request.method == 'DELETE':
cat.delete()
return HttpResponse(status=204)

else:
return HttpResponse(status=400)


models.py:



class Category(models.Model):
name = models.CharField(max_length=25, blank=False)

class Meta:
ordering = ('id',)


serializers.py:



class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'name')


urls.py:



urlpatterns = [
path('category/<int:pk>/', views.category_instance)
]


I've tried to look for similar issues that other people may have had, but I was unable to construct a solution to my problem.




Traceback:



Internal Server Error: /category/1/
Traceback (most recent call last):
File "C:UsersvaidaDocumentsCodingandroid-tm-apivenvlibsite-packagesdjangocorehandlersexception.py", line 34,
in inner
response = get_response(request)
File "C:UsersvaidaDocumentsCodingandroid-tm-apivenvlibsite-packagesdjangocorehandlersbase.py", line 126, in
_get_response
response = self.process_exception_by_middleware(e, request)
File "C:UsersvaidaDocumentsCodingandroid-tm-apivenvlibsite-packagesdjangocorehandlersbase.py", line 124, in
_get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:UsersvaidaDocumentsCodingandroid-tm-apivenvlibsite-packagesdjangoviewsdecoratorscsrf.py", line 54, i
n wrapped_view
return view_func(*args, **kwargs)
File "C:UsersvaidaDocumentsCodingandroid-tm-apiandroid_tm_apiapiviews.py", line 146, in category_instance
serializer = CategorySerializer(cat, data=request.data)
AttributeError: 'WSGIRequest' object has no attribute 'data'









share|improve this question



















  • 1




    Please add your server error log
    – Mohammad Umair
    Nov 11 at 19:59







  • 5




    Why are you not using django-rest-framework.org/api-guide/generic-views/… ?
    – Mohammad Umair
    Nov 11 at 20:00










  • I've included a traceback to the post. To be honest I was following a django-rest-framework tutorial on setting up an API and was not aware of the generic-views.
    – somekid
    Nov 11 at 20:11






  • 1




    The error is raised before serializer.save, so nothing should get saved in this request. In any case, the error message explains what's wrong. request does not have a data attribute. Maybe you mean request.body? If you use django-rest-framework's built in generic views or modelviewsets, all this error handling is already implemented. The drf docs contain tutorials and examples of how to use the generic views.
    – Håken Lid
    Nov 11 at 20:46






  • 1




    @HåkenLid Thank you. I resolved the issue by replacing the views with generic class-based views
    – somekid
    Nov 11 at 21:45














up vote
2
down vote

favorite












I'm fairly new to Django REST framework and I've tried to write an API for my mobile application. I'm facing an issue where a PUT request works fine (updates data) apart from the fact it returns response 500 (Internal Server Error). Some guidance towards resolving this would be much appreciated.



views.py:



@csrf_exempt
def category_instance(request, pk):
"""
Returns Category instance
"""
try:
cat = Category.objects.get(pk=pk)
except Category.DoesNotExist:
return HttpResponse("Error: category does not exist", status=404)

if request.method == 'GET':
serializer = CategorySerializer(cat, many=False)
return JsonResponse(serializer.data, safe=False)

elif request.method == 'PUT':
serializer = CategorySerializer(cat, data=request.data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, 200)
return JsonResponse(serializer.errors, status=400)

elif request.method == 'DELETE':
cat.delete()
return HttpResponse(status=204)

else:
return HttpResponse(status=400)


models.py:



class Category(models.Model):
name = models.CharField(max_length=25, blank=False)

class Meta:
ordering = ('id',)


serializers.py:



class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'name')


urls.py:



urlpatterns = [
path('category/<int:pk>/', views.category_instance)
]


I've tried to look for similar issues that other people may have had, but I was unable to construct a solution to my problem.




Traceback:



Internal Server Error: /category/1/
Traceback (most recent call last):
File "C:UsersvaidaDocumentsCodingandroid-tm-apivenvlibsite-packagesdjangocorehandlersexception.py", line 34,
in inner
response = get_response(request)
File "C:UsersvaidaDocumentsCodingandroid-tm-apivenvlibsite-packagesdjangocorehandlersbase.py", line 126, in
_get_response
response = self.process_exception_by_middleware(e, request)
File "C:UsersvaidaDocumentsCodingandroid-tm-apivenvlibsite-packagesdjangocorehandlersbase.py", line 124, in
_get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:UsersvaidaDocumentsCodingandroid-tm-apivenvlibsite-packagesdjangoviewsdecoratorscsrf.py", line 54, i
n wrapped_view
return view_func(*args, **kwargs)
File "C:UsersvaidaDocumentsCodingandroid-tm-apiandroid_tm_apiapiviews.py", line 146, in category_instance
serializer = CategorySerializer(cat, data=request.data)
AttributeError: 'WSGIRequest' object has no attribute 'data'









share|improve this question



















  • 1




    Please add your server error log
    – Mohammad Umair
    Nov 11 at 19:59







  • 5




    Why are you not using django-rest-framework.org/api-guide/generic-views/… ?
    – Mohammad Umair
    Nov 11 at 20:00










  • I've included a traceback to the post. To be honest I was following a django-rest-framework tutorial on setting up an API and was not aware of the generic-views.
    – somekid
    Nov 11 at 20:11






  • 1




    The error is raised before serializer.save, so nothing should get saved in this request. In any case, the error message explains what's wrong. request does not have a data attribute. Maybe you mean request.body? If you use django-rest-framework's built in generic views or modelviewsets, all this error handling is already implemented. The drf docs contain tutorials and examples of how to use the generic views.
    – Håken Lid
    Nov 11 at 20:46






  • 1




    @HåkenLid Thank you. I resolved the issue by replacing the views with generic class-based views
    – somekid
    Nov 11 at 21:45












up vote
2
down vote

favorite









up vote
2
down vote

favorite











I'm fairly new to Django REST framework and I've tried to write an API for my mobile application. I'm facing an issue where a PUT request works fine (updates data) apart from the fact it returns response 500 (Internal Server Error). Some guidance towards resolving this would be much appreciated.



views.py:



@csrf_exempt
def category_instance(request, pk):
"""
Returns Category instance
"""
try:
cat = Category.objects.get(pk=pk)
except Category.DoesNotExist:
return HttpResponse("Error: category does not exist", status=404)

if request.method == 'GET':
serializer = CategorySerializer(cat, many=False)
return JsonResponse(serializer.data, safe=False)

elif request.method == 'PUT':
serializer = CategorySerializer(cat, data=request.data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, 200)
return JsonResponse(serializer.errors, status=400)

elif request.method == 'DELETE':
cat.delete()
return HttpResponse(status=204)

else:
return HttpResponse(status=400)


models.py:



class Category(models.Model):
name = models.CharField(max_length=25, blank=False)

class Meta:
ordering = ('id',)


serializers.py:



class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'name')


urls.py:



urlpatterns = [
path('category/<int:pk>/', views.category_instance)
]


I've tried to look for similar issues that other people may have had, but I was unable to construct a solution to my problem.




Traceback:



Internal Server Error: /category/1/
Traceback (most recent call last):
File "C:UsersvaidaDocumentsCodingandroid-tm-apivenvlibsite-packagesdjangocorehandlersexception.py", line 34,
in inner
response = get_response(request)
File "C:UsersvaidaDocumentsCodingandroid-tm-apivenvlibsite-packagesdjangocorehandlersbase.py", line 126, in
_get_response
response = self.process_exception_by_middleware(e, request)
File "C:UsersvaidaDocumentsCodingandroid-tm-apivenvlibsite-packagesdjangocorehandlersbase.py", line 124, in
_get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:UsersvaidaDocumentsCodingandroid-tm-apivenvlibsite-packagesdjangoviewsdecoratorscsrf.py", line 54, i
n wrapped_view
return view_func(*args, **kwargs)
File "C:UsersvaidaDocumentsCodingandroid-tm-apiandroid_tm_apiapiviews.py", line 146, in category_instance
serializer = CategorySerializer(cat, data=request.data)
AttributeError: 'WSGIRequest' object has no attribute 'data'









share|improve this question















I'm fairly new to Django REST framework and I've tried to write an API for my mobile application. I'm facing an issue where a PUT request works fine (updates data) apart from the fact it returns response 500 (Internal Server Error). Some guidance towards resolving this would be much appreciated.



views.py:



@csrf_exempt
def category_instance(request, pk):
"""
Returns Category instance
"""
try:
cat = Category.objects.get(pk=pk)
except Category.DoesNotExist:
return HttpResponse("Error: category does not exist", status=404)

if request.method == 'GET':
serializer = CategorySerializer(cat, many=False)
return JsonResponse(serializer.data, safe=False)

elif request.method == 'PUT':
serializer = CategorySerializer(cat, data=request.data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, 200)
return JsonResponse(serializer.errors, status=400)

elif request.method == 'DELETE':
cat.delete()
return HttpResponse(status=204)

else:
return HttpResponse(status=400)


models.py:



class Category(models.Model):
name = models.CharField(max_length=25, blank=False)

class Meta:
ordering = ('id',)


serializers.py:



class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'name')


urls.py:



urlpatterns = [
path('category/<int:pk>/', views.category_instance)
]


I've tried to look for similar issues that other people may have had, but I was unable to construct a solution to my problem.




Traceback:



Internal Server Error: /category/1/
Traceback (most recent call last):
File "C:UsersvaidaDocumentsCodingandroid-tm-apivenvlibsite-packagesdjangocorehandlersexception.py", line 34,
in inner
response = get_response(request)
File "C:UsersvaidaDocumentsCodingandroid-tm-apivenvlibsite-packagesdjangocorehandlersbase.py", line 126, in
_get_response
response = self.process_exception_by_middleware(e, request)
File "C:UsersvaidaDocumentsCodingandroid-tm-apivenvlibsite-packagesdjangocorehandlersbase.py", line 124, in
_get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:UsersvaidaDocumentsCodingandroid-tm-apivenvlibsite-packagesdjangoviewsdecoratorscsrf.py", line 54, i
n wrapped_view
return view_func(*args, **kwargs)
File "C:UsersvaidaDocumentsCodingandroid-tm-apiandroid_tm_apiapiviews.py", line 146, in category_instance
serializer = CategorySerializer(cat, data=request.data)
AttributeError: 'WSGIRequest' object has no attribute 'data'






python django python-3.x django-rest-framework






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 20:10

























asked Nov 11 at 19:57









somekid

318




318







  • 1




    Please add your server error log
    – Mohammad Umair
    Nov 11 at 19:59







  • 5




    Why are you not using django-rest-framework.org/api-guide/generic-views/… ?
    – Mohammad Umair
    Nov 11 at 20:00










  • I've included a traceback to the post. To be honest I was following a django-rest-framework tutorial on setting up an API and was not aware of the generic-views.
    – somekid
    Nov 11 at 20:11






  • 1




    The error is raised before serializer.save, so nothing should get saved in this request. In any case, the error message explains what's wrong. request does not have a data attribute. Maybe you mean request.body? If you use django-rest-framework's built in generic views or modelviewsets, all this error handling is already implemented. The drf docs contain tutorials and examples of how to use the generic views.
    – Håken Lid
    Nov 11 at 20:46






  • 1




    @HåkenLid Thank you. I resolved the issue by replacing the views with generic class-based views
    – somekid
    Nov 11 at 21:45












  • 1




    Please add your server error log
    – Mohammad Umair
    Nov 11 at 19:59







  • 5




    Why are you not using django-rest-framework.org/api-guide/generic-views/… ?
    – Mohammad Umair
    Nov 11 at 20:00










  • I've included a traceback to the post. To be honest I was following a django-rest-framework tutorial on setting up an API and was not aware of the generic-views.
    – somekid
    Nov 11 at 20:11






  • 1




    The error is raised before serializer.save, so nothing should get saved in this request. In any case, the error message explains what's wrong. request does not have a data attribute. Maybe you mean request.body? If you use django-rest-framework's built in generic views or modelviewsets, all this error handling is already implemented. The drf docs contain tutorials and examples of how to use the generic views.
    – Håken Lid
    Nov 11 at 20:46






  • 1




    @HåkenLid Thank you. I resolved the issue by replacing the views with generic class-based views
    – somekid
    Nov 11 at 21:45







1




1




Please add your server error log
– Mohammad Umair
Nov 11 at 19:59





Please add your server error log
– Mohammad Umair
Nov 11 at 19:59





5




5




Why are you not using django-rest-framework.org/api-guide/generic-views/… ?
– Mohammad Umair
Nov 11 at 20:00




Why are you not using django-rest-framework.org/api-guide/generic-views/… ?
– Mohammad Umair
Nov 11 at 20:00












I've included a traceback to the post. To be honest I was following a django-rest-framework tutorial on setting up an API and was not aware of the generic-views.
– somekid
Nov 11 at 20:11




I've included a traceback to the post. To be honest I was following a django-rest-framework tutorial on setting up an API and was not aware of the generic-views.
– somekid
Nov 11 at 20:11




1




1




The error is raised before serializer.save, so nothing should get saved in this request. In any case, the error message explains what's wrong. request does not have a data attribute. Maybe you mean request.body? If you use django-rest-framework's built in generic views or modelviewsets, all this error handling is already implemented. The drf docs contain tutorials and examples of how to use the generic views.
– Håken Lid
Nov 11 at 20:46




The error is raised before serializer.save, so nothing should get saved in this request. In any case, the error message explains what's wrong. request does not have a data attribute. Maybe you mean request.body? If you use django-rest-framework's built in generic views or modelviewsets, all this error handling is already implemented. The drf docs contain tutorials and examples of how to use the generic views.
– Håken Lid
Nov 11 at 20:46




1




1




@HåkenLid Thank you. I resolved the issue by replacing the views with generic class-based views
– somekid
Nov 11 at 21:45




@HåkenLid Thank you. I resolved the issue by replacing the views with generic class-based views
– somekid
Nov 11 at 21:45












1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










The issue was resolved by replacing the views with generic class-based views instead.






share|improve this answer




















  • Why method based function was not working ?
    – Mohammad Umair
    Nov 12 at 5:16










  • I'm still not completely sure as I've had an API in the past which seemed to work fine with it.
    – somekid
    Nov 12 at 18:32










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53252648%2fdjango-rest-framework-put-request-returns-500-but-updates-data%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
1
down vote



accepted










The issue was resolved by replacing the views with generic class-based views instead.






share|improve this answer




















  • Why method based function was not working ?
    – Mohammad Umair
    Nov 12 at 5:16










  • I'm still not completely sure as I've had an API in the past which seemed to work fine with it.
    – somekid
    Nov 12 at 18:32














up vote
1
down vote



accepted










The issue was resolved by replacing the views with generic class-based views instead.






share|improve this answer




















  • Why method based function was not working ?
    – Mohammad Umair
    Nov 12 at 5:16










  • I'm still not completely sure as I've had an API in the past which seemed to work fine with it.
    – somekid
    Nov 12 at 18:32












up vote
1
down vote



accepted







up vote
1
down vote



accepted






The issue was resolved by replacing the views with generic class-based views instead.






share|improve this answer












The issue was resolved by replacing the views with generic class-based views instead.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 11 at 21:47









somekid

318




318











  • Why method based function was not working ?
    – Mohammad Umair
    Nov 12 at 5:16










  • I'm still not completely sure as I've had an API in the past which seemed to work fine with it.
    – somekid
    Nov 12 at 18:32
















  • Why method based function was not working ?
    – Mohammad Umair
    Nov 12 at 5:16










  • I'm still not completely sure as I've had an API in the past which seemed to work fine with it.
    – somekid
    Nov 12 at 18:32















Why method based function was not working ?
– Mohammad Umair
Nov 12 at 5:16




Why method based function was not working ?
– Mohammad Umair
Nov 12 at 5:16












I'm still not completely sure as I've had an API in the past which seemed to work fine with it.
– somekid
Nov 12 at 18:32




I'm still not completely sure as I've had an API in the past which seemed to work fine with it.
– somekid
Nov 12 at 18:32

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53252648%2fdjango-rest-framework-put-request-returns-500-but-updates-data%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Barbados

How to read a connectionString WITH PROVIDER in .NET Core?

Node.js Script on GitHub Pages or Amazon S3