【问题标题】:Page not found erro with drf-nested-routersdrf-nested-routers 找不到页面错误
【发布时间】:2018-10-29 20:51:50
【问题描述】:

我正在使用

Django: 2.0  
Djanfo REST Frameword: 3.8.2
drf-nested-routers: 0.90.2

我的contacts/views.py

class ContactViewSet(viewsets.ModelViewSet):
    serializer_class = ContactSerializer
    permission_classes = (IsAuthenticated,)

    def get_queryset(self):
        return Contact.objects.filter(user=self.request.user)

class ContactPhoneNumberViewSet(viewsets.ModelViewSet):
    serializer_class = ContactPhoneNumberSerializer
    permission_classes = (IsAuthenticated,)

    def get_queryset(self):
        print(self.kwargs)
        phone_numbers = ContactPhoneNumber.objects.all()
        return phone_numbers

app/urls.py

from rest_framework_nested import routers

from contacts.views import ContactViewSet, ContactPhoneNumberViewSet

router = routers.SimpleRouter()
router.register(r'contacts', ContactViewSet, 'contacts')
contact_router = routers.NestedSimpleRouter(router, r'contacts', lookup='contact')
contact_router.register(r'phone_number', ContactPhoneNumberViewSet, base_name='contact-phone-numbers')

api_urlpatterns = [
    path('', include(router.urls)),
]

urlpatterns = [
    path('api/', include(api_urlpatterns)),
    url(r'^admin/', admin.site.urls),
]

使用此设置,我可以访问

/api/contacts/           # <= list all contacts
/api/contacts/<pk>/      # <= contact detail

但是在尝试访问时

/api/contacts/<pk>/phone_number/           # <= list all phone numbers

它给出了Page Not Found 错误。

我也尝试传递&lt;phone_number_pk&gt;,但仍然收到Page not Found 错误。

【问题讨论】:

    标签: django django-rest-framework drf-nested-routers


    【解决方案1】:
    api_urlpatterns = [
        path('', include(router.urls)),
        path('', include(contact_router.urls)),
    ]
    

    你还需要单独注册嵌套的url

    【讨论】:

      猜你喜欢
      • 2019-08-07
      • 2015-11-24
      • 1970-01-01
      • 2018-03-11
      • 2020-11-15
      • 2014-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多