This is my code in Views.py
class NotificationsViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
queryset = Notifications.objects.all()
serializer_class = NotificationsSerializer
filter_fields = ('status','task','survey_type',)
def put(self, request, pk, format=None):
notifications = self.get_object(pk)
serializer = NotificationsSerializer(notifications, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
notifications = self.get_object(pk)
notifications.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
When i try to use method PUT i got error put() takes at least 3 arguments (2 given). What is wrong with my code?
def put(self, request, pk, format=None):
It takes 3 arguments at the minimum. Like:
self.put(request, pk)
self variable needs to be passed.
Alternatively,
put(self, request, pk)
Or 4 arguments at the max,
self.put(request, pk, format)
That's probably because you're doing a PUT on the set entry point where the pk isn't defined. Make it optional:
def put(self, request, pk=None, format=None):
Note that there's no point in using viewset if you're overriding put.
Related
Right now I'm overriding the whole retrieve and update function. I want to override only that part, it does not ask for the pk value. Thanks
View.py
class EmployeeView(generics.RetrieveUpdateAPIView):
permission_classes = [EmployeePermission]
serializer_class = EmployeeSerializers
def retrieve(self, request, *args, **kwargs):
employee = Employee.objects.get(user=self.request.user)
serializer = EmployeeSerializers(employee)
return Response(serializer.data)
def update(self, request, *args, **kwargs):
employee_user = Employee.objects.get(user=self.request.user)
serializer = EmployeeSerializers(employee_user, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)strong text
urls.py
path('viewEmployee/', views.EmployeeView.as_view()),
what you need is to override the get_queryset method, and write your custom filtering, then django will take care of otherthings.
class EmployeeView(generics.RetrieveUpdateAPIView):
queryset = Employee.objects.all()
permission_classes = [EmployeePermission]
serializer_class = EmployeeSerializers
def get_queryset(self):
return super().get_queryset().filter(
user=self.request.user
)
I am very new to Python and Django. I have this app that returns 4 different types of transport routes (In the code I only showed two, cause they basically are the same...).
These 4 views use the same class-based views, but only the models' names are different. As they all return the same functionality(get, post, put and delete) I ended up repeating the same code over and over again.
Is there any way I can refactor it simpler?
Any help is appreciated! Thank you :)
views.py
********* tube view ***********
class TubeListView(APIView):
def get(self, _request, format=None):
tubeRoutes = TubeRoute.objects.all()
serialized_with_user = NestedTubeRouteSerializer(tubeRoutes, many=True)
return Response(serialized_with_user.data)
def post(self, request, format=None):
request.data['traveler'] = request.user.id
serializer = TubeRouteSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE)
class TubeDetailView(APIView):
def get(self, _request, pk, format=None):
tubeRoute = TubeRoute.objects.get(pk=pk)
serialized_with_user = NestedTubeRouteSerializer(tubeRoute)
return Response(serialized_with_user.data)
def put(self, request, pk, format=None):
request.data['traveler'] = request.user.id
tubeRoute = self.get_object(pk)
if tubeRoute.owner.id != request.user.id:
return Response(status=status.HTTP_401_UNAUTHORIZED)
updated_serializer = TubeRouteSerializer(tubeRoute)
if updated_serializer.is_valid():
updated_serializer.save()
return Response(updated_serializer.data, status=status.HTTP_200_OK)
return Response(updated_serializer.errors, status=status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE)
def delete(self, request, pk, format=None):
tubeRoute = self.get_object(pk)
if tubeRoute.owner.id != request.user.id:
return Response(status=status.HTTP_401_UNAUTHORIZED)
tubeRoute.delete()
return Response(status=status.HTTP_200_OK)
********* bus view ***********
class BusListView(APIView):
def get(self, _request, format=None):
busRoutes = BusRoute.objects.all()
serialized_with_user = NestedBusRouteSerializer(busRoutes, many=True)
return Response(serialized_with_user.data)
def post(self, request, format=None):
request.data['traveler'] = request.user.id
serializer = BusRouteSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE)
class BusDetailView(APIView):
def get(self, _request, pk, format=None):
busRoute = BusRoute.objects.get(pk=pk)
serialized_with_user = NestedBusRouteSerializer(busRoute)
return Response(serialized_with_user.data)
def put(self, request, pk, format=None):
request.data['traveler'] = request.user.id
busRoute = self.get_object(pk)
if busRoute.owner.id != request.user.id:
return Response(status=status.HTTP_401_UNAUTHORIZED)
updated_serializer = BusRouteSerializer(busRoute)
if updated_serializer.is_valid():
updated_serializer.save()
return Response(updated_serializer.data, status=status.HTTP_200_OK)
return Response(updated_serializer.errors, status=status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE)
def delete(self, request, pk, format=None):
busRoute = self.get_object(pk)
if busRoute.owner.id != request.user.id:
return Response(status=status.HTTP_401_UNAUTHORIZED)
busRoute.delete()
return Response(status=status.HTTP_200_OK)
You should take a look to these class based views in DRF.
For instance, the following code should be enough to replace your first TubeListView:
from rest_framework import generics
class TubeListView(generics.ListCreateAPIView):
queryset = TubeRoute.objects.all()
serializer_class = NestedTubeRouteSerializer
def post(self, request, *args, **kwargs):
request.data['traveler'] = request.user.id
return super().post(self, request, *args, **kwargs)
If you don't need any special behavior, you don't have to redefine get, post, etc methods. But if you need to change data, for instance in your POST method, you can do your stuff and then call the usual behavior of the superclass with super().post(self, request, *args, **kwargs)
I would recommend checking Viewsets in Django Rest Framework, specifically ModelViewset.
The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy() which coincide with the following:
get ----> .retrieve()
list ----> .list()
post ----> .create()
patch ----> .partial_update()
put ----> .update()
delete ----> .destroy()
Let me provide a case using the Bus Views
The Modelviewset form would be:
class BusViewset(ModelViewset):
queryset = BusRoute.objects.all()
serializer_class = NestedBusRouteSerializer
def get_queryset(self):
return self.queryset.filter(
owner__id=self.request.user.id
)
For the permission checks you implemented, Django Rest Framework has a Permissions System that takes care of that. For you own use case, a custom permission would be sufficient.
I have a DRF class with a single method get_queryset(). I would like to add caching to the serialized queryset by intercepting the request before get_queryset gets called, but after custom middleware/authentication has been run. Here is a trivial example of what I'm after:
class FooList(generics.ListCreateAPIView)
permission_classes = (permissions.IsAuthenticated,)
serializer_class = FooSerializer
def intercept_for_caching(self):
user = self.request.meta_data['user']
cached_data = cache.get(f'FooStuff:{user.pk}')
if cached_data:
return Response(cached_data)
else:
new_data = ? # retrieve serialized queryset
cache.set(f'FooStuff:{user.pk}', new_data)
return Response(new_data)
def get_queryset(self):
user = self.request.meta_data['user']
return Foo.objects.filter(user=user)
Are there any methods I can hook into?
I am aware that cache_page is designed for this use case (https://www.django-rest-framework.org/api-guide/caching/), but I haven't been able to get it to work with our custom middeleware.
The source code has a function list:
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
I was able to cache the queryset by overriding list:
def list(self, request, *args, **kwargs):
user = self.request.user
cache = caches['redis']
cache_key = f'my_cache:{user.pk}'
cached_results = cache.get(cache_key)
if cached_results:
return Response(cached_results)
else:
queryset = self.filter_queryset(self.get_queryset())
serializer = self.get_serializer(queryset, many=True)
cache.set(cache_key, serializer.data)
return Response(serializer.data)
I'm using Django 1.11 and I'm having a issue with path parameters.
I'm getting an error like this for all requests involving path parameters.
Error:
TypeError at /posts/2
get() missing 1 required positional argument: 'pk'
urls.py
...
url(r'^posts',PostView.as_view()),
url(r'^posts/<int:pk>/',PostView.as_view()),
...
views.py
..
#-------- API for CRUD -----------------#
class PostView(APIView):
permission_classes = (IsAuthenticated,)
def get_object(self,pk,user_id):
try:
return Post.objects.get(pk=pk,user_id=user_id)
except Post.DoesNotExist:
raise Http404
def get(self,request,pk):
post = Post.objects.get(user=request.user.id)
serializer = PostSerializer(post)
return Response({"success":True,"data":serializer.data},status=status.HTTP_200_OK)
def put(self, request, pk):
post = self.get_object(pk,request.user.id)
serializer = PostSerializer(post, data=request.data)
if serializer.is_valid():
serializer.save(user=request.user.id)
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self,request):
params = request.data
params['user'] = request.user.id
serializer = PostSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
saved_data = self.perform_create(serializer)
post = PostSerializer(saved_data)
return Response({"success":True, "message":"Post Added Successfully","data":post.data}, status=status.HTTP_201_CREATED)
def perform_create(self, serializer):
return serializer.save()
...
url example :
GET : localhost:8000/posts/2
Can someone tell me how to pass positional parameters.
In above code you are using user_id, pk as positional arguments in request methods and view method get_object. pk and user_id is available across the view. you can use them like self.kwargs.get('pk'), self.request.user.pk.
Please check the code below for implementation details.
class PostView(APIView):
permission_classes = (IsAuthenticated,)
def get_object(self):
pk = self.kwargs.get('pk')
user_id = self.request.id
try:
return Post.objects.get(pk=pk,user_id=user_id)
except Post.DoesNotExist:
raise Http404
def get(self,request, *args, **kwargs):
# ...
pass
def put(self, request, *args, **kwargs):
# ...
pass
def post(self,request, *args, **kwargs):
# ...
pass
Your get and post signatures only accept a self and request parameter, whereas these here should include the pk parameter of your URL. Since you defined the same view for a URL without the pk parameter, you should make these parameters optional (so add a default value, in case these are missing). Like:
class PostView(APIView):
permission_classes = (IsAuthenticated,)
def get_object(self,pk,user_id):
# ...
pass
def get(self,request, pk=None):
# ...
pass
def put(self, request, pk=None):
# ...
pass
def post(self,request, pk=None):
# ...
pass
An alternative is to provide kwargs in the URL with the missing parameter, like:
path(r'posts',PostView.as_view(), kwargs={'pk': None}),
path(r'posts/<int:pk>/',PostView.as_view())
or for pre-django-2.0 installations, you need to define this as a regex:
url(r'^posts/$',PostView.as_view(), kwargs={'pk': None}),
url(r'^posts/(?P<pk>[0-9]+)/',PostView.as_view())
Views.py
class UserPoints(ListAPIView):
queryset = UserAttributes.objects.all()
serializer_class = UserPointsSerializer
OR
def get(self, request, pk, format=None):
UserAttributes = self.get_object(id)
serializer = UserPointsSerializer(UserAttributes)
return Response(serializer.data)
Serializers.py
class UserPointsSerializer(serializers.ModelSerializer):
username = serializers.Field(source='User')
class Meta:
model = UserAttributes
fields = [
'points',
]
I want to get the point associated with a particular user when I send a GET Request with username as a parameter.
You need to call .is_valid() on the serializer
def get(self, request, pk, format=None):
user_attributes = UserAttribute.objects.get(id=id)
serializer = UserPointsSerializer(data=user_attributes)
if serializer.is_valid():
return Response(serializer.data)