Django CreateView请求传递

时间:2018-12-01 16:47:55

标签: django django-forms

我正在使用django-better-form。一个强大的多表单支持工具。一个问题是我想将request传递给模型表单。我使用kwargs.pop("request")面对KeyError。如何解决这个问题

我的forms.py:

class FooForm(forms.ModelForm):
    class Meta:
        model = Foo
        fields = '__all__'
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        super(FooForm, self).__init__(*args, **kwargs)

class BarForm(forms.ModelForm):
    class Meta:
        model = Bar
        fields = '__all__'


class FooBarMultiForm(MultiModelForm):
    form_classes = {
        'foo': FooForm,
        'bar': BarForm,
    }

views.py

class PassRequestToFormViewMixin:
    def get_form_kwargs(self):
        kwargs = super(PassRequestToFormViewMixin, self).get_form_kwargs()
        kwargs['request'] = self.request
        return kwargs

class FooCreateView(PassRequestToFormViewMixin, CreateView):
    form_class = FooBarMultiForm
    template_name = 'template.html'
    success_url = reverse_lazy('list')

1 个答案:

答案 0 :(得分:1)

您可以通过get_forms_kwargs将请求传递给表单:

class SomeView(FormView):

    def get_form_kwargs(self):
        kwargs = super(SomeView, self).get_form_kwargs()
        kwargs['request'] = self.request
        return kwargs

并以以下形式捕获它:

class FooForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        super(FooForm, self).__init__(*args, **kwargs)        

    class Meta:
        model = Foo
        fields = '__all__'


class BarForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
       self.request = kwargs.pop("request")  # Need to pop here as well, even if you don't need it
       super(BarForm, self).__init__(*args, **kwargs) 

    class Meta:
        model = Bar
        fields = '__all__'


class FooBarMultiForm(MultiModelForm):
    form_classes = {
        'foo': FooForm,
        'bar': BarForm,
    }

    def get_form_args_kwargs(self, key, args, kwargs):
        fargs, fkwargs = super(FooBarMultiForm, self).get_form_args_kwargs(key, args, kwargs)  # call super
        fkwargs.update({'request': kwargs.get('request')})  # update form kwargs with request
        return fargs, fkwargs