Django:将kwargs参数从get_context_data()添加到ModelForm

时间:2018-11-07 16:21:09

标签: django django-forms kwargs

我想使用kwargs并将kwargs元素从Django CBV传递到__init__中的表单文件中。

我有一个View class和一个get_context_data(),可以提取用户输入的电子邮件:

class HomeView(FormView):

    form_class = CustomerForm

    def get_context_data(self, **kwargs):

        if "DocumentSelected" in self.request.GET:
            customer_email = self.request.GET['EmailDownloadDocument']
            kwargs['customer_email'] = customer_email

        return super(HomeView, self).get_context_data(**kwargs)

我有一个带有这一部分的forms.py文件

class CustomerForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        customer_email = kwargs.pop('customer_email', None)
        super(CustomerForm, self).__init__(*args, **kwargs)
        if customer_email is not None:
            self.fields['email'].initial = customer_email
            self.fields['first_name'].initial = Customer.objects.get(email__iexact=customer_email).first_name
            self.fields['last_name'].initial = Customer.objects.get(email__iexact=customer_email).last_name
            self.fields['country'].initial = Customer.objects.get(email__iexact=customer_email).country_id
            self.fields['institution'].initial = Customer.objects.get(email__iexact=customer_email).institution

    class Meta:
        model = Customer
        fields = ['email', 'first_name', 'last_name', 'country', 'institution']
        widgets = {
            'email': forms.TextInput(attrs={'placeholder': _('name@example.com')}),
            'first_name': forms.TextInput(attrs={'placeholder': _('First Name')}),
            'last_name': forms.TextInput(attrs={'placeholder': _('Last Name')}),
            'institution': forms.TextInput(attrs={'placeholder': _('Agency, company, academic or other affiliation')}),
        }

但是,当我的None打印电子邮件地址时,它会在我的表单文件中返回get_context_data()

这部分有问题吗?

1 个答案:

答案 0 :(得分:2)

get_context_data方法创建用于呈现模板的上下文字典。如果您要将多余的垃圾传递给表单,请使用get_form_kwargs

class HomeView(FormView):

    form_class = CustomerForm

    def get_form_kwargs(self):
        kwargs = super(HomeView, self).get_form_kwargs()
        if "DocumentSelected" in self.request.GET:
            customer_email = self.request.GET['EmailDownloadDocument']
            kwargs['customer_email'] = customer_email
        return kwargs