I am using Django Rest Framework to upload a file
My view file looks like this:
class FileViewSet(viewsets.ModelViewSet):
queryset = Files.objects.all()
serializer_class = FilesSerializer
#+++++++++++++++++++++++++++++++++++++
parser_classes = (MultiPartParser, FormParser)
def post(self, request, *args, **kwargs):
serializer = FilesSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=HTTP_201_CREATED)
else:
return Response(serializer.error, status=HTTP_400_BAD_REQUEST)
My view works well with file upload even if there is no bottom part of the comment.
So why should I use the code under the comment?
I used the translator.
Please understand if there is a mistake.
Your code is working without the post function because ModelViewSet class(i.e the one you inherited in your FileViewSet) already has implementations of various actions like list(),create(), retrieve(), update() etc.
So when you are hitting post request for uploading the file, create() action gets called automatically and will save the file by taking values provided by you in class variables like serializer_class,parser_classes etc.
Read more about ModelViewSet:
Related
My api was set to api/barrel/details/<int:pk> originally but i want to make the delete function into api/barrel (which only have get and post function) without parsing the pk
class BarrelAPIView(APIView):
def get(self,request):
barrel = Barrel.objects.all() #queryset
serializer = BarrelSerializer(barrel, many=True)
return Response(serializer.data)
def post(self,request):
serializer = BarrelSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self,request):
try:
data = request.data
Barrel.objects.filter(code=data['code']).delete()
return Response(status=status.HTTP_204_NO_CONTENT)
except Exception as error:
return Response( status=status.HTTP_400_BAD_REQUEST)
It can be done on postman by parsing the 'code'. but when i try on restframework default api browser the delete button showed up but nothing happens after that
You should check out:
https://www.django-rest-framework.org/api-guide/generic-views/#mixins
in the long run it will make your life easier..
The url could have any structure you like.
I would also suggest to refer to:
Two scoops of Django that introduce you to various tips, tricks, patterns, code snippets, and techniques
I'm new to DRF. While defining a HyperlinkedRelatedField in serializer class like this:
class JournalistSerializer(serializers.ModelSerializer):
articles = serializers.HyperlinkedRelatedField(view_name="article-
detail")
im getting the following error:
`HyperlinkedRelatedField` requires the request in the serializer
context. Add `context={'request': request}` when instantiating the
serializer.
when i add context={'request': request} in the related APIView class:
class JournalistListCreateAPIView(APIView):
def get(self,request):
journalist = Journalist.objects.all()
serializer = JournalistSerializer(journalist,many=True,context=
{'request':request})
return Response(serializer.data)
the HyperLink in the APIView works fine. But i dont understand why request has to be sent while instantiating the serializer. Please help me understand.
It does require request in context as it builds absolute URL
to be more concrete it is used get_url serializer method
def get_url(self, obj, view_name, request, format):
...
return self.reverse(view_name, kwargs=kwargs, request=request, format=format)
I'm using a Generic CreateAPIView to save a model in the database. Here's my code:
class AppointmentCreateAPIView(generics.CreateAPIView):
permission_classes = (AppointmentCreatePermission,)
queryset = Appointment.objects.all()
serializer_class = AppointmentSerializer
And in my urls.py file, I have this:
urlpatterns[
url(r'^appointments/create', AppointmentCreateAPIView.as_view()),
]
This url obviously supports the POST operation. However, I want to use this same url to handle a GET request, which would fetch the data necessary to populate the appointment creation form. I understand that I can use separate urls for get and post, but that's not what I'm looking for. Is it possible that I keep the same url, but with different HTTP Verb, the view would be able to handle both GET and POST request?
You can do this by manually adding get method to your view, it would look something like this. Code below probably will not work, but will give you general idea.
from rest_framework.response import Response
class AppointmentCreateAPIView(generics.CreateAPIView):
permission_classes = (AppointmentCreatePermission,)
queryset = Appointment.objects.all()
serializer_class = AppointmentSerializer
def get(self, request, *args, **kwargs):
serializer = AppointmentSerializer({your_data})
return Response(serializer.data)
Im trying to perform partial update in DRF using angular $http.
In my DRF model viewset i override the partial_update function (server side).
class AnimalTreatmentViewSet(viewsets.ModelViewSet):
queryset = MyObject.objects.all()
serializer_class = MyObjectSerializer
def create(self, request):
# It works with $http.post()
pass
def update(self, request, pk=None):
# It works with $http.put()
pass
def list(self, request):
# It works with $http.get()
pass
def partial_update(self, request, pk=None):
# This one wont work with $http.patch()
instance = self.get_object()
serializer = self.serializer_class(instance, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
In the client side angular handle the user request.
$http.patch('/api/my_viewset_url/1', data);
But i got this response Method Not Allowed (PATCH): /api/my_viewset_url/1
When using $http.get() request with DRF model viewset list(self, request) it works well for getting a list same goes for $http.post() with def create(self, request) for creating object and $http.put() with def update(self, request) for updating object.
What's wrong? or what is the correct http verb for partial_update in DRF model viewset
It seems like the URL is missing a trailing slash.
Related documentation:
By default the URLs created by SimpleRouter/DefaultRouter are appended with a
trailing slash. This behavior can be modified by setting the trailing_slash argument to False when instantiating the router. For example:
router = routers.DefaultRouter(trailing_slash=False)
I am using the Django REST framework in order to implement a game server for an android game. I have written a class, that is derived from GenericAPIView to handle a specific Http Post request. I want the request to return a list of some objects, that were previously queried from the database.
My code looks like this:
class NewGameView(GenericAPIView):
serializer_class=NewGameRequestSerializer
def post(self, request, format=None):
serializer = NewGameRequestSerializer(data=request.DATA)
if serializer.is_valid():
req=serializer.save()
mygamedata=...; # request game data objects
serializer = MyGameDataSerializer(mygamedata, many=True)
return Response(serializer.data,status=status.HTTP_201_CREATED)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)
When I access this view via curl, everything works as expected. However, when I submit using the Django generated "browsable api" form, I am receiving a
'ListSerializer' object is not iterable
error during "template rendering". If I derive my class from APIView instead, the error does not occur, but Django will not display the forms anymore (for whatever reason).
Can anyone explain what is going on?
Thanks
You can just return a dictionary with the data you need.
class NewGameView(GenericAPIView):
serializer_class=NewGameRequestSerializer
def post(self, request, format=None):
serializer = NewGameRequestSerializer(data=request.DATA)
if serializer.is_valid():
req=serializer.save()
mygamedata=...; # request game data objects
data = {'game_name': mygame_object.name}
return Response(data,status=status.HTTP_201_CREATED)