Python rest_framework.viewsets.ModelViewSet() Examples

The following are 13 code examples of rest_framework.viewsets.ModelViewSet(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rest_framework.viewsets , or try the search function .
Example #1
Source File: test_serializer_introspector.py    From py2swagger with MIT License 6 votes vote down vote up
def test_default_serializer(self):
        if StrictVersion(VERSION) >= StrictVersion('3.0.0'):
            return

        from rest_framework.viewsets import ModelViewSet
        from django.http import HttpRequest
        from testapp.models import TestModel

        class TestViewSet(ModelViewSet):
            model = TestModel

        view = TestViewSet()
        view.request = HttpRequest()

        si = SerializerIntrospector(view.get_serializer_class())

        self.assertEqual(si.name, 'TestModelSerializer') 
Example #2
Source File: django_app.py    From scout_apm_python with MIT License 6 votes vote down vote up
def drf_router():
    """
    DRF Router as a lazy object because it needs to import User model which
    can't be done until after django.setup()
    """
    from django.contrib.auth.models import User
    from rest_framework import routers
    from rest_framework import serializers
    from rest_framework import viewsets

    class UserSerializer(serializers.Serializer):
        id = serializers.IntegerField(label="ID", read_only=True)
        username = serializers.CharField(max_length=200)

    class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserSerializer

    router = routers.SimpleRouter()
    router.register(r"users", UserViewSet)
    return router 
Example #3
Source File: generic_testcase_helper.py    From iguana with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def view_and_template(self, view, template, address_pattern, address_kwargs=None, get_kwargs=None):
    if get_kwargs:
        response = self.client.get(reverse(address_pattern, kwargs=address_kwargs),  get_kwargs, follow=True)
    else:
        response = self.client.get(reverse(address_pattern, kwargs=address_kwargs), follow=True)
    if template:
        self.assertTemplateUsed(response, template)

    # catch the APIViewsTest for ProjectViewSet that need additional address_kwargs
    if issubclass(view, viewsets.ModelViewSet):
        self.assertEqual(response.resolver_match.func.__name__, view.as_view(address_kwargs).__name__)
    else:
        self.assertEqual(response.resolver_match.func.__name__, view.as_view().__name__)
    return response


# \param address_pattern the pattern for the reverse lookup that is used to resolve the target address
# \param address_kwargs optional additional kwargs arguments that might be needed for the resolving of the address
# \param get_kwargs optional additional kwargs for a get request that might be needed
#        to specify which content is desired
# \param alternate_error_message optional error message that is shown instead of the default error message 
Example #4
Source File: yasg.py    From django-bananas with MIT License 6 votes vote down vote up
def get_tags(self, operation_keys):
        view = self.view
        meta = self.view.get_admin_meta()
        tags = {"app:{label}".format(label=meta.app_label)}

        if self.is_navigation():
            tags.add("navigation")

        if issubclass(view.__class__, viewsets.ModelViewSet):
            tags.add("crud")

        view_method = getattr(view, view.action, None)
        if view_method:
            include_tags = set(getattr(view_method, "include_tags", None) or [])
            exclude_tags = set(getattr(view_method, "exclude_tags", None) or [])
            tags |= include_tags
            tags -= exclude_tags

        return [tag for tag in tags if tag not in meta.exclude_tags] 
Example #5
Source File: test_urlparser.py    From py2swagger with MIT License 5 votes vote down vote up
def test_format_api_patterns_url_import_with_routers(self):

        class MockApiViewSet(ModelViewSet):
            serializer_class = CommentSerializer
            model = User
            queryset = User.objects.all()

        class AnotherMockApiViewSet(ModelViewSet):
            serializer_class = CommentSerializer
            model = User
            queryset = User.objects.all()

        router = DefaultRouter()
        router.register(r'other_views', MockApiViewSet, base_name='test_base_name')
        router.register(r'more_views', AnotherMockApiViewSet, base_name='test_base_name')

        urls_app = patterns('', url(r'^', include(router.urls)))
        urls = patterns(
            '',
            url(r'api/', include(urls_app)),
            url(r'test/', include(urls_app))
        )
        apis = self.urlparser.get_apis(urls)

        self.assertEqual(
            4, sum(api['path'].find('api') != -1 for api in apis))
        self.assertEqual(
            4, sum(api['path'].find('test') != -1 for api in apis)) 
Example #6
Source File: test_urlparser.py    From py2swagger with MIT License 5 votes vote down vote up
def test_exclude_router_api_root(self):
        class MyViewSet(ModelViewSet):
            serializer_class = CommentSerializer
            queryset = User.objects.all()
            model = User

        router = DefaultRouter()
        router.register('test', MyViewSet, base_name='test_base_name')

        urls_created = len(router.urls)

        apis = self.urlparser.get_apis(router.urls)

        self.assertEqual(4, urls_created - len(apis)) 
Example #7
Source File: api_endpoint.py    From django-rest-framework-docs with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def is_method_allowed(self, callback_cls, method_name):
        has_attr = hasattr(callback_cls, method_name)
        viewset_method = (issubclass(callback_cls, ModelViewSet) and
                          method_name in VIEWSET_METHODS.get(self.callback.suffix, []))

        return has_attr or viewset_method 
Example #8
Source File: test_access_policy.py    From drf-access-policy with MIT License 5 votes vote down vote up
def test_get_invoked_action_from_class_based_view(self):
        class UserViewSet(ModelViewSet):
            pass

        policy = AccessPolicy()
        view_instance = UserViewSet()
        view_instance.action = "create"

        result = policy._get_invoked_action(view_instance)
        self.assertEqual(result, "create") 
Example #9
Source File: api.py    From django-carrot with Apache License 2.0 5 votes vote down vote up
def create(self, request: Request, *args, **kwargs) -> viewsets.ModelViewSet.create:
        """
        Create a new `ScheduledTask` object
        """
        return super(ScheduledTaskViewset, self).create(request, *args, **kwargs) 
Example #10
Source File: api.py    From django-carrot with Apache License 2.0 5 votes vote down vote up
def update(self, request: Request, *args, **kwargs) -> viewsets.ModelViewSet.update:
        """
        Update an existing `ScheduledTask` object
        """
        return super(ScheduledTaskViewset, self).update(request, *args, **kwargs) 
Example #11
Source File: api.py    From django-carrot with Apache License 2.0 5 votes vote down vote up
def run(self, request: Request, *args, **kwargs) -> viewsets.ModelViewSet.retrieve:
        """
        Triggers a given scheduled task now
        """
        _object = self.get_object()
        _object.publish()
        return self.retrieve(request, *args, **kwargs) 
Example #12
Source File: test_rest_framework.py    From django-rules with MIT License 5 votes vote down vote up
def setUp(self):
        from testapp.models import TestModel

        class TestModelSerializer(ModelSerializer):
            class Meta:
                model = TestModel
                fields = "__all__"

        class TestViewSet(AutoPermissionViewSetMixin, ModelViewSet):
            queryset = TestModel.objects.all()
            serializer_class = TestModelSerializer
            permission_type_map = AutoPermissionViewSetMixin.permission_type_map.copy()
            permission_type_map["custom_detail"] = "add"
            permission_type_map["custom_nodetail"] = "add"

            @action(detail=True)
            def custom_detail(self, request):
                return Response()

            @action(detail=False)
            def custom_nodetail(self, request):
                return Response()

            @action(detail=False)
            def unknown(self, request):
                return Response()

        self.model = TestModel
        self.vs = TestViewSet
        self.req = APIRequestFactory().get("/")
        self.req.user = AnonymousUser() 
Example #13
Source File: test_unit.py    From drf-schema-adapter with MIT License 5 votes vote down vote up
def test_get_base_viewset(self):

        class DummyViewSet(ModelViewSet):
            pass

        class OtherDummyViewSet(ModelViewSet):
            pass

        class DummyEndpoint(Endpoint):
            model = Product
            base_viewset = DummyViewSet

        class DummyReadOnlyEndpoint(DummyEndpoint):
            read_only = True

        class OtherDummyReadOnlyEndpoint(Endpoint):
            model = Product
            read_only = True
            base_viewset = OtherDummyViewSet
            base_readonly_viewset = DummyViewSet

        dummy = DummyEndpoint()
        self.assertTrue(issubclass(dummy.get_base_viewset(), DummyViewSet))

        dummy = DummyReadOnlyEndpoint()
        self.assertTrue(issubclass(dummy.get_base_viewset(), DummyViewSet))

        dummy = OtherDummyReadOnlyEndpoint()
        self.assertTrue(issubclass(dummy.get_base_viewset(), DummyViewSet))