52566

Django rest framework- calling another class-based view

<h3>Question</h3>

I have pored over several similar posts (and Calling a class-based view of an app from another app in same project seemed promising, but does not work), but some are older and none quite work for me. Here's my setup (using Django==2.0.6, djangorestframework==3.8.2)

I have a basic model (simplified here):

from django.db import models class Resource(models.Model): name = models.CharField(max_length=100, null=False)

I have a basic endpoint where I can list and create Resource instances:

from rest_framework import generics, permissions from myapp.models import Resource from myapp.serializers import ResourceSerializer class ListAndCreateResource(generics.ListCreateAPIView): queryset = Resource.objects.all() serializer_class = ResourceSerializer permission_classes = (permissions.IsAuthenticated,)

(afaik, the details of the serializer are not relevant, so that is left out).

Anyway, in addition to that basic endpoint, I have another API endpoint which performs some actions, but also creates some Resource objects in the process. Of course, I would like to make use of the functionality encapsulated in the ListAndCreateResource class so I only have to maintain one place where Resources are created.

I have tried:

Attempt 1:

class SomeOtherView(generics.CreateAPIView): def post(self, request, *args, **kwargs): # ... some other functionality... # ... response = ListAndCreateResource().post(request, *args, **kwargs) # ... more functionality... return Response({'message': 'ok'})

Unfortunately, that does not work for me. In my trace, I get:

File "/home/projects/venv/lib/python3.5/site-packages/rest_framework/generics.py", line 111, in get_serializer kwargs['context'] = self.get_serializer_context() File "/home/projects/venv/lib/python3.5/site-packages/rest_framework/generics.py", line 137, in get_serializer_context 'request': self.request, AttributeError: 'ListAndCreateResource' object has no attribute 'request'

Attempt 2: This attempt tries to use the as_view method which is part of all Django class-based views:

class SomeOtherView(generics.CreateAPIView): def post(self, request, *args, **kwargs): # ... some other functionality... # ... response = ListAndCreateResource.as_view()(request, *args, **kwargs) # ... more functionality... return Response({'message': 'ok'})

But that gives up with:

AssertionError: The `request` argument must be an instance of `django.http.HttpRequest`, not `rest_framework.request.Request`

So my question is...is there a straightforward way to do this? I can access the _request attribute of the rest_framework.request.Request object (which is of type django.http.HttpRequest, but then I do not have any of the authentication details that are contained in the DRF Request object (indeed, my ListAndCreateResource returns a 403 if I use response = ListAndCreateResource().as_view()(request._request, *args, **kwargs) in attempt #2 above).

Thanks in advance!


<h3>Answer1:</h3>

You can access the request with self.request in class based views.

来源:https://stackoverflow.com/questions/51145652/django-rest-framework-calling-another-class-based-view

Recommend

  • background color of cells in QTableview, PySide2
  • mysql8.0.17远程连接
  • Entity Framework 4.1 Custom Database Initializer strategy
  • Liquibase : link main yaml changelog from test
  • Filtering lists
  • Excel 2013 VBA Pivot Table Select Only Top 5 Items With Ties
  • Mocking System class method using testng, mockito and powermock
  • Read line in file, print line if it contains string
  • How to deploy a theme in liferay?
  • reactjs - Input defaultValue is set but not showing
  • How to show images with horizontal scrolling android
  • I am unable to upload App Icon file in Facebook Console
  • How to stop Neo4j community edition
  • Java Generics - When to use “T” and “?” [closed]
  • How to split string from meshed content and add html element
  • @Valid is not triggering - Spring MVC 3.2
  • QuickLook class not working
  • How to insert values from dynamically added rows into database
  • android - how to use/set up nested spinners?
  • Error 0 when using ftplib
  • Scrapy and submitting a javascript form
  • Javascript matrix inversion
  • Canvas: Trying to use a recycled bitmap error
  • Sending big file using FileInputStream/ObjectOutputStream
  • Producer consumer code with wait/notify doesn't work on second produce
  • Invalidate ASP.NET Identity 2.0 login without removing the application cookie
  • Sphinx4 ConfidenceResult and SpeechResult
  • Is there a better approach to use BeautifulSoup in my python web crawler codes?
  • ASP.NET grid in 2.0 having trouble with paging to retain value of check box on save button click
  • jQuery update image src on hover
  • How do we add new button to gmail compose bar in chrome extension? Is it through javascript or some
  • about iOS target version and SDK version
  • Comparing a large set of images by content
  • Scrapy + Selenium + Datepicker
  • Special characters (ë) in JSON-response
  • Finding all XML nodes between each two processing instructions
  • How to display youtube video on HTML page? [closed]
  • convert json to excel in java