简体   繁体   中英

How can I reuse a DRF class-based views POST method?

Now I want to reuse the post method of BundleList. Either I find out the absolute URL and use requests.post(URL) to send a request.

The 2nd way is to reuse by return BundleList.as_view()(request) in a view function. But I can't set request.data = data . Request data is immutable.

When I try to use

url = reverse_lazy(BundleList.as_view(), request=request)
print(f"{url = }")

It just gives me:

NoReverseMatch at /generateSampleBundle/
Reverse for 'my_app.views.BundleList' not found. 'my_app.views.BundleList' is not a valid view function or pattern name.

The BundleList is a class-based view with get and post method.

drfurlpatterns = [  # DRF URL endpoints
    path('bundles/', views.BundleList.as_view()),
]

Can anyone help me out?

You should set name for your view and use that name in reverse_lazy()

for ex:

drfurlpatterns = [  # DRF URL endpoints
    path('bundles/', views.BundleList.as_view()), name='bundle-list'
]

then

url = reverse_lazy('bundle-list', request=request)

see, docs

Also, to know why request.data is sometimes immutable see this question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM