【问题标题】:How to pass non default argument with default arguments in python django forms如何在 python django 表单中使用默认参数传递非默认参数
【发布时间】:2013-02-20 21:23:20
【问题描述】:

这是我的代码

class FarticlesWizard(FormWizard):

    def done(self,request,form_list):

        if request.method=='POST':
            form1=F1articles(request.POST)  
            form2=F2articles(request.POST)
            form_dict={}
            for x in form_list:
                form_dict=dict(form_dict.items()+x.cleaned_data.items())
                insert_db=Marticles(heading = form_dict['heading'],
                                    content = form_dict['content'],
                                    created_by=request.session['user_name'],    
                                    country=form_dict['country'],
                                    work=form_dict['work'])
                insert_db.save()
            return HttpResponseRedirect('/display/')

但我现在需要传递 def done(self,request,id=None, form_list): 其中 id 是非默认参数...我收到错误消息 non-default argument follows default argument (views.py, line 130) 有没有办法做到这一点?

【问题讨论】:

  • 与问题无关,但您能否在格式化代码时使用 pep8 - 在分配变量名称的位置的“=”前后放置空格 - 这将提高代码的可读性。

标签: python django django-forms django-views django-formwizard


【解决方案1】:

没有。正如错误消息所暗示的那样,任何具有默认值的参数都必须位于所有没有默认值的参数之后。

为什么你觉得你需要像这样在中间添加新参数?为什么不直接做def done(self, request, form_list, id=None)?在中间添加一个新参数将破坏所有使用位置参数调用该函数的现有代码。

【讨论】:

    【解决方案2】:

    默认参数都必须在非默认参数之后,否则位置参数传递会被搞砸。如果你有def done(self,request,id=None,form_list): 并且你在某个地方调用done(r,fl),python 不知道 fl 是进入 id 还是 form_list。您总是必须指定 id 才能指定 form_list。这就是为什么默认参数都放在最后的原因,比如def done(self,request,form_list,id=None)

    【讨论】:

      猜你喜欢
      • 2012-08-01
      • 1970-01-01
      • 2019-12-14
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 2020-09-04
      相关资源
      最近更新 更多