【问题标题】:missing 1 required positional argument: 'request'缺少 1 个必需的位置参数:“请求”
【发布时间】:2018-07-11 18:29:24
【问题描述】:

这是我的观点.py

class categAdmin(admin.ModelAdmin):

    change_form_template = 'category_forms.html'
    list_display = ['title']
    model = Category
    fields = ['status','title','category_post','body', 'photo', 
    'url','slider','Gallery','lists','pk_tree','video','maps']

    # def render_change_form(self, request, context,  **kwargs):
    #     post = Post.objects.all()
    #     context['eve'] = post
    #     return super(categAdmin,self).render_change_form(request, context, **kwargs)

    def item_add(request, self, post_id):
        tree = post_id
        return self.add_view(request, extra_context={'tree': tree})

我收到错误 item_add() 缺少 1 个必需的位置参数:'request'

【问题讨论】:

  • 你交换了selfrequest 参数......
  • 此外,你在哪里打电话给item_add?看起来您在没有request 对象的情况下调用它...

标签: python django


【解决方案1】:

您需要交换selfrequest 参数。

def item_add(self, request, post_id):
    tree = post_id
    ...

【讨论】:

    【解决方案2】:

    永远记住方法是绑定到对象的,每当你调用方法时,python 都会隐式地将 self 参数(调用方法的对象)传递给方法调用,在你的例子中:

    class CategAdmin:
          def item_add(self, request, post_id):
               pass
    

    将是签名格式,注意 self 对象是方法签名中的第一个参数。所以当你这样做时

    categoryAdmin = CategAdmin()
    categoryAdmin.item_add(request,123)
    this is what will be called by the python interpreter CategAdmin.item_add(categoryAdmin,request,123)
    

    另一个反馈是改进您的编码风格,即遵循一些约定,例如始终以大写字母开头的类名,为类、方法和变量赋予有意义的名称。 这使您的代码更具可读性,并且通过此调试将更快。

    干杯!

    【讨论】:

      猜你喜欢
      • 2021-08-12
      • 2018-01-24
      • 2020-05-07
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-12
      相关资源
      最近更新 更多