Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name “user-detail”

前端 未结 17 1366
感动是毒
感动是毒 2020-11-28 03:11

I am building a project in Django Rest Framework where users can login to view their wine cellar. My ModelViewSets were working just fine and all of a sudden I get this frus

17条回答
  •  春和景丽
    2020-11-28 03:46

    I came across this error too and solved it as follows:

    The reason is I forgot giving "**-detail" (view_name, e.g.: user-detail) a namespace. So, Django Rest Framework could not find that view.

    There is one app in my project, suppose that my project name is myproject, and the app name is myapp.

    There is two urls.py file, one is myproject/urls.py and the other is myapp/urls.py. I give the app a namespace in myproject/urls.py, just like:

    url(r'', include(myapp.urls, namespace="myapp")),
    

    I registered the rest framework routers in myapp/urls.py, and then got this error.

    My solution was to provide url with namespace explicitly:

    class UserSerializer(serializers.HyperlinkedModelSerializer):
        url = serializers.HyperlinkedIdentityField(view_name="myapp:user-detail")
    
        class Meta:
            model = User
            fields = ('url', 'username')
    

    And it solved my problem.

提交回复
热议问题