如何将用户ID从视图传递到Form的init方法?

时间:2018-06-23 23:30:59

标签: django python-3.x

我已经审查了数小时的许多问题/答案,并应用了许多技术,但是我无法将用户ID传递给 init ()方法的形式,它总是会出现诸如“ init ()收到了意外的关键字参数“ request””。有人知道原因吗?

表格,根据评论的要求进行了更新:

class ChildChoreForm(ModelForm):
  class Meta:
    model = ChildChore
    exclude = ('child',)
    fields = '__all__'

  def __init__(self, *args, **kwargs):
    self.request = kwargs.pop('request', None)
    super(ChildChoreForm, self).__init__(*args, **kwargs)
    self.fields['chore'].queryset = Chore.objects.filter(created_by=self.request.user)

ChildChoreFormSet = inlineformset_factory(Child,  ChildChore, form=ChildChoreForm, extra=1)

查看:

class ChildChoreUpdate(UpdateView):
  model = Child
  success_url = reverse_lazy('children-list') 
  form_class = ChildChoreFormSet

  def get_form_kwargs(self):
    kwargs = super().get_form_kwargs()
    if hasattr(self, 'object'):
        kwargs.update({'request': self.request})
    return kwargs

打开updaet网页后出现的错误:

Internal Server Error: /chore/children/23
Traceback (most recent call last):
  File "C:\Python\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
    response = get_response(request)
  File "C:\Python\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Python\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Python\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\Python\lib\site-packages\django\views\generic\base.py", line 69, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Python\lib\site-packages\django\views\generic\base.py", line 89, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 190, in get
    return super().get(request, *args, **kwargs)
  File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 133, in get
    return self.render_to_response(self.get_context_data())
  File "C:\Python\py_projects\children_chores\chore\views.py", line 202, in get_context_data
    data = super(ChildChoreUpdate, self).get_context_data(**kwargs )
  File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data
    kwargs['form'] = self.get_form()
  File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 33, in get_form
    return form_class(**self.get_form_kwargs())
  File "C:\Python\lib\site-packages\django\forms\models.py", line 898, in __init__
    super().__init__(data, files, prefix=prefix, queryset=qs, **kwargs)
  File "C:\Python\lib\site-packages\django\forms\models.py", line 569, in __init__
    super().__init__(**defaults)
TypeError: __init__() got an unexpected keyword argument 'request'
Internal Server Error: /chore/children/23
Traceback (most recent call last):
  File "C:\Python\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
    response = get_response(request)
  File "C:\Python\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Python\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Python\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\Python\lib\site-packages\django\views\generic\base.py", line 69, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Python\lib\site-packages\django\views\generic\base.py", line 89, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 190, in get
    return super().get(request, *args, **kwargs)
  File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 133, in get
    return self.render_to_response(self.get_context_data())
  File "C:\Python\py_projects\children_chores\chore\views.py", line 202, in get_context_data
    data = super(ChildChoreUpdate, self).get_context_data(**kwargs )
  File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data
    kwargs['form'] = self.get_form()
  File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 33, in get_form
    return form_class(**self.get_form_kwargs())
  File "C:\Python\lib\site-packages\django\forms\models.py", line 898, in __init__
    super().__init__(data, files, prefix=prefix, queryset=qs, **kwargs)
  File "C:\Python\lib\site-packages\django\forms\models.py", line 569, in __init__
    super().__init__(**defaults)
TypeError: __init__() got an unexpected keyword argument 'request'

1 个答案:

答案 0 :(得分:0)

问题是您已将表单设置为接受request中的__init__参数,但是您正在初始化 formset ,而不是 form < / em>。您需要将表单集修改为accept that same argument并将其传递给表单集中的表单:

# First define a base class that overrides __init__ and get_form_kwargs
from django.forms import BaseFormSet

class BaseChildChoreFormSet(BaseFormSet):

    def __init__(self, *args, **kwargs):
        # Handle the request argument that you are passing on init
        self.request = kwargs.pop('request', None)
        super().__init__(*args, **kwargs)

    def get_form_kwargs(self, index):
        kwargs = super().get_form_kwargs(index)
        # Add request to the kwargs that are passed to the form on init
        kwargs['request'] = self.request
        return kwargs

# Now set up your formset using this class
ChildChoreFormSet = inlineformset_factory(
    Child,  ChildChore, form=ChildChoreForm, formset=BaseChildChoreFormSet, extra=1)