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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With