How to override the CRUD methods in tastypie? - python

As the title suggests I'd like to know if and how I can override the get and post methods of Tastypie.
For example, every time a user sends over a json file at the API endpoint, I don't want anything to be stored in the models and instead only return a small message back.
How can I do this?
Thanks.

This example coming directly from Tastypie Cookbook:
from tastypie.utils import now
class MyResource(ModelResource):
class Meta:
queryset = MyObject.objects.all()
def get_object_list(self, request):
return super(MyResource, self).get_object_list(request).filter(start_date__gte=now)
Similar approach can be utilized for POST etc. as well. Hope it helps :)

Related

Django Rest Framework ListCreateAPIView not checking has_object_permissions?

I've been trying to figure this out for almost a full day now, and I can't seem to figure out why has_object_permission method isn't called when the ListCreateAPIView is called in DRF. I've tried all the solutions I could find, but according to the docs check_object_permissions is called in this class already.
I know it has to be something stupid I'm missing. Code snippets are below, please help!
views.py:
from accountability.models import AccountabilityItem
from accountability.serializers import AccountabilityItemSerializer
from rest_framework import generics
from .permissions import InGroup
class AccountabilityItemListCreate(generics.ListCreateAPIView):
queryset = AccountabilityItem.objects.all()
serializer_class = AccountabilityItemSerializer
permission_classes = (InGroup,)
permissions.py:
from rest_framework import permissions
class InGroup(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
print('Checking for object')
return False
Another note, I've added the has_permission method to the permissions.py file, and this method runs all the time no matter what.
Thanks!
Calling has_object_permission doesn't make sense for lists. It is intended for single instances.
What you want is to filter your list of objects so it only leaves those for which the user has some permissions. DjangoObjectPermissionsFilter does it but requires django-guardian. You might get a similar result but creating your own filtering class (sources for DjangoObjectPermissionsFilter)

return list of ids in a Get. Django Rest Framework

I have a model called "document-detail-sample" and when you call it with a GET, something like this, GET https://url/document-detail-sample/ then you get every "document-detail-sample".
Inside the model is the id. So, if you want every Id, you could just "iterate" on the list and ask for the id. Easy.
But... the front-end Developers don't want to do it :D they say it's too much work...
So, I gotta return the id list. :D
I was thinking something like GET https://url/document-detail-sample/id-list
But I don't know how to return just a list. I read this post and I know how to get the id_list in the backend. But I don't know what should I implement to just return a list in that url...
the view that I have it's pretty easy:
class DocumentDetailSampleViewSet(viewsets.ModelViewSet):
queryset = DocumentDetailSample.objects.all()
serializer_class = DocumentDetailSampleSerializer
and the url is so:
router.register(r'document-detail-sample', DocumentDetailSampleViewSet)
so:
1- is a good Idea do it with an url like .../document-detail-sample/id-list" ?
2- if yes, how can I do it?
3- if not, what should I do then?
You could use #list_route decorator
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response
class DocumentDetailSampleViewSet(viewsets.ModelViewSet):
queryset = DocumentDetailSample.objects.all()
serializer_class = DocumentDetailSampleSerializer
#list_route()
def id_list(self, request):
q = self.get_queryset().values('id')
return Response(list(q))
This decorator allows you provide additional endpoint with the same name as a method. /document-detail-sample/id_list/
reference to docs about extra actions in a viewset
Assuming you don't need pagination, just override the list method like so
class DocumentDetailSampleViewSet(viewsets.ModelViewSet):
queryset = DocumentDetailSample.objects.all()
serializer_class = DocumentDetailSampleSerializer
def list(self, request):
return Response(self.get_queryset().values_list("id", flat=True))

django-rest-framework non orm-based filtering

I am using DjangoRestApi and while it works like a charm with queryset (orm-based) views, I am struggling to make views that use different back-end to behave same way orm-based views are. Notably I want to add filters and have them cast and validated automatically.
Pseudo code below:
class NewsFilter(django_filters.FilterSet):
category = django_filters.NumberFilter(name='category')
limit = django_filters.NumberFilter(name='limit')
page = django_filters.NumberFilter(name='page')
class NewsView(generics.APIView):
filter_class = NewsFilter
def get(self, request):
filters = self.filter_class(??) # not sure, what to put here
payload = logic.get_business_news(**filters.data) # same
return Response(payload, status=status.HTTP_200_OK)
Any hint how to tackle problem will be appreciated.
Ultimate goal is to:
user types something into url or sends via POST, django-rest intercepts relevant values, extracts them, casts them into correct type and return as a dictionary
filters are displayed as they would if serializer was ORM based
The function signature to any single filter is like
class MyFilter(django_filters.Filter):
def filter(self,queryset,value):
[...]
The function signature to a FilterSet is:
def __init__(self, data=None, queryset=None, prefix=None, strict=None):
So, it looks like you pass in request.GET as data param and then pass in your queryset.

Permission class on #detail_route not working, Django Rest Framework

I'm new to DRF, but I'm trying to use a permission class on a #detail_route using the method in this stack thread: Using a permission class on a detail route
My code currently looks like this :
#detail_route(methods=['GET'], permission_classes=[IsStaffOrRestaurantUser])
def restaurant_dishes_ready_for_pickup(self, request, pk=None):
...stuff....
class IsStaffOrRestaurantUser(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
print(request)
print(view)
print(obj)
return False
The print statements never get executed... I'm probably missing something but I've looked through the documentation and can't really figure it out, is my approach right at all? Thanks!
EDIT:
I realize in our code already that we have this snippet in our Viewset, is it possible to override this in the decorator?
def get_permissions(self):
# Limit to listing and getting for non Admin user
if self.request.method in permissions.SAFE_METHODS:
return (permissions.AllowAny(),)
return (IsAdminUser(),)
Not sure if it's the most elegant solution, but you might be able to upgrade get_permissions() like so:
def get_permissions(self):
# check additional route specifics
path = self.request.path
if ("restaurant_dishes_ready_for_pickup" in path):
return (IsStaffOrRestaurantUser,)
# Limit to listing and getting for non Admin user
if (self.request.method in permissions.SAFE_METHODS):
return (permissions.AllowAny,)
return (IsAdminUser,)
PS: Also maybe return permission class objects instead of instances in get_permissions().
Quote from the documentation:
If you're writing your own views and want to enforce object level permissions, or if you override the get_object method on a generic view, then you'll need to explicitly call the .check_object_permissions(request, obj) method on the view at the point at which you've retrieved the object.
So you'll need to call explicitly the permission check.
Note that you could have that for free if you were using a RetrieveAPIView instead of a function based view for example.

Django related User Model - Permissions and Decorators

i am a beginner to Django i am trying to use permissions to permit access to specific view functions via a decorator, for specific user types only. Right now i am totaly confused by all kinds of stuff i have read about and seam not to figure out how i should do this.
I have two different kinds of users let it be UserTypeONE and UserTypeTWO.
UserTypeONE and UserTypeTWO should have access to specific views only.
Here is my code:
myuserTypes.py
class UserTypeONE(models.Model):
lieOtO_User = models.OneToOneField(settings.AUTH_USER_MODEL)
lie_SomeAttribute= models.CharField(max_length=300, help_text ='Name')
class Meta:
permissions = (('Can_View_MyShop', 'Can see Shop View'),)
class UserTypeTWO(models.Model):
lieOtO_User = models.OneToOneField(settings.AUTH_USER_MODEL)
lie_SomeOtherAttribute= models.CharField(max_length=300, help_text ='Name')
class Meta:
permissions = (('Can_View_Targets', 'Can see the Targets'),)
Here is what i am trying to do in my views.py
#login_required
#permission_required('UserTypeONE.Can_View_MyShop', raise_exception=True)
def MyShopView(request):
#do something
i also tried
#user_passes_test(lambda u: u.usertypeone.permission('Can_View_MyShop'))
As you guys can see i am an absolute beginner unfortunately all documentations and examples havent done me any good instead i am even more confused.
I would really appreciate help on this.
I would use user_passes_test() here since you specifically want to restrict specific views.
First, define a couple of functions that return True when you're dealing with a user who should be able to see your content. It looks like your UserTypeOne and UserTypeTwo models extend the base User model with a one-to-one relationship, so you can use hasattr to check if a given base user has one of those attributes:
def type_one_only(user):
if hasattr (user, 'usertypeone'):
return True
else:
return False
def type_two_only(user):
#same thing without if/else
return hasattr(user, 'usertypetwo')
Now when you have a view that you want to restrict to one user type, you can add a user_passes_test decorator before it:
#user_passes_test(type_one_only, login_url='/')
def my_view(request):
...
login_url is where a user will be sent if they do not pass the test you've indicated.

Categories