【问题标题】:With Django REST framework, how do I parse a RESTful string parameter?使用 Django REST 框架,如何解析 RESTful 字符串参数?
【发布时间】:2021-08-22 16:54:24
【问题描述】:

我正在使用 Python 3.9 和

Django==3.1.4
djangorestframework==3.12.2

我想将一个安静的参数(“作者”字符串)传递给我的 GET 方法。在我的 urls.py 文件中,我有

urlpatterns = [
    ...
    path('user/<str:author>', views.UserView.as_view()),

然后在我的 UserView 类(在我的 views.py 文件中定义)中,我有

class UserView(APIView):
    def get(self, request):
        ...
        author = self.kwargs.get('author', None)

但是当我执行时

GET http://localhost:8000/user/myauthor

我得到了错误

TypeError: get() got an unexpected keyword argument 'author'

我还需要做什么才能正确访问 URL 中的 RESTful 参数?

【问题讨论】:

    标签: django django-rest-framework parameters restful-url


    【解决方案1】:

    要使用 url 模式中添加的路径参数,您必须将 **kwargs 作为额外参数添加到 get() 方法中。您的视图应如下所示:

    class UserView(APIView):
        def get(self, request, **kwargs):
           ...
           author = kwargs.get('author', None)
    

    【讨论】:

      【解决方案2】:

      get() 方法也应该接受 url 参数,您可以使用 *args**kwargs 语法来确保无论您如何命名参数都可以正常工作:

      class UserView(APIView):
          def get(self, request, *args, **kwargs):
              ...
              author = self.kwargs.get('author', None)
      

      【讨论】:

      • 你应该使用kwargs而不是self.kwargs
      猜你喜欢
      • 2017-03-19
      • 2016-06-11
      • 2018-09-07
      • 2018-02-11
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      相关资源
      最近更新 更多