Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django : Add kwargs parameters from get_context_data() to ModelForm

I would like to use kwargs and pass kwargs element from Django CBV to my form file in the __init__.

I have a View class with get_context_data() which let to pick up email input, filled by user :

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)

And I have a forms.py file with this part

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': _('[email protected]')}),
            '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')}),
        }

However it returns None in my form file while my get_context_data() prints the email address.

Something is wrong in this part ?

like image 536
Essex Avatar asked Oct 27 '25 23:10

Essex


1 Answers

The get_context_data method creates the context dict used to render the template. Use get_form_kwargs if you want to pass extra kwargs to the form.

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
like image 107
Alasdair Avatar answered Oct 30 '25 16:10

Alasdair