I would like to limit which categories a user is able to upload a picture to based on certain criteria. In the following code, I am able to do what I want on the website.
class PhotoUploadForm(forms.ModelForm):
class Meta:
model = Photo
fields = ('photo', 'category')
def __init__(self, *args, **kwargs):
if not hasattr(self, 'request'):
self.request = kwargs.pop('request')
super(PhotoUploadForm, self).__init__(*args, **kwargs)
if not self.request.user.edu_email:
self.fields['category'].queryset = Category.objects.exclude(
title='University')
However, I do not know how to mimic this in the Django Rest Framework to use in my API. Would anyone happen to know how to do this?
Thank you in advance!
serializer:
class PhotoCreateSerializer(serializers.ModelSerializer):
class Meta:
model = Photo
fields = [
'creator',
'photo',
'category',
]
view:
class PhotoCreateAPIView(generics.CreateAPIView):
serializer_class = PhotoCreateSerializer
答案 0 :(得分:2)
DRF提供permission_classes
来限制特定用户。
from rest_framework.permissions import IsAuthenticated
class PhotoUploadPermissions(IsAuthenticated):
""" write custom permissions here"""
def has_permission(self, request, view):
if not request.user.edu_email:
queryset = view.get_queryset()
category_exclude = queryset.exclude(title='University')
if category_exclude:
return True
else:
return False
class PhotoCreateAPIView(viewsets.ModelViewSet):
queryset = Category.objects.all()
permission_classes = (PhotoUploadPermissions,)
serializer_class = PhotoCreateSerializer
答案 1 :(得分:1)
在 PhotoCreateAPIView :
中添加此内容def get_queryset(self):
if not self.request.user.edu_email:
return Category.objects.exclude(
title='University')