重写UpdateView的get_form_kwargs()方法

时间:2019-07-08 18:54:26

标签: python django

我想覆盖UpdateView的get_form_kwargs()方法,并具有类似于以下内容的东西:

class GroupRatingView(UpdateView):
    model = Group
    fields = ['rating']

    def get_form_kwargs(self, *args, **kwargs):
        kwargs = super(GroupRatingView, self).get_form_kwargs(*args, **kwargs)
        import ipdb; ipdb.set_trace()

但是,如果我尝试此操作,则会出现以下错误:

File "/venv/lib/python2.7/site-packages/django/views/generic/edit.py" in post
  181.         form = self.get_form()

File "/venv/lib/python2.7/site-packages/django/views/generic/edit.py" in get_form
  45.         return form_class(**self.get_form_kwargs())

Exception Type: TypeError at /groups/5/rate
Exception Value: ModelFormMetaclass object argument after ** must be a mapping, not NoneType

似乎self.get_form_kwargs()返回了None,而我希望能进入调试器。为什么我出现错误而不是点击调试器跟踪?

1 个答案:

答案 0 :(得分:3)

您忘记了在方法末尾返回kwargs;这会导致该方法返回None(不是映射,并导致错误)。

向您的方法添加return语句:

class GroupRatingView(UpdateView):
    ...

    def get_form_kwargs(self, *args, **kwargs):
        kwargs = super(GroupRatingView, self).get_form_kwargs(*args, **kwargs)
        ...
        return kwargs