简体   繁体   中英

django: same url but different verbs in Classed based view

Is it good to write urls.py as following:

urlpatterns = [
    url(r'^v1/files/$', FileView.as_view(), name='api-upload'),
    url(r'^v1/files/(?P<pk>\d+)$', FileView.as_view(), name='api-delete'),
    url(r'^v1/files/$', FileView.as_view(), name='api-view-all'),
    url(r'^v1/files/(?P<pk>\d+)$', FileView.as_view(), name='api-view-one'),
]

The second one and the forth one are nearly the same. But one is DELETE, the other is GET.

Any suggestions to improve it? Thanks. Is it possible to reverse the URL by django.core.urlresolvers? just like the following

'deleteUrl': reverse('upload-delete', args=[instance.pk]),

You don't need to write urls, you just need to define two methods in your view:

# views.py

class FileView(...):

    def get(self, request, *args, **kwargs):
        # This method will catch the GET call

    def delete(self, request, *args, **kwargs):
        # This method will catch the DELETE call

With this, you will need only one url config:

url(r'^v1/files/(?P<pk>\d+)$', FileView.as_view(), name='api-file')

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