Conditional statements in DRF CreateAPIView

时间:2015-09-14 15:42:21

标签: django serialization django-forms django-views django-rest-framework

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

2 个答案:

答案 0 :(得分:2)

DRF提供permission_classes来限制特定用户。

permission.py

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

viewsets.py

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')