gpt4 book ai didi

Django : Add kwargs parameters from get_context_data() to ModelForm

转载 作者:行者123 更新时间:2023-12-05 04:03:52 24 4
gpt4 key购买 nike

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

我有一个带有 get_context_data()View class,它可以获取由用户填写的电子邮件输入:

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')}),
}

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

这部分有什么问题吗?

最佳答案

get_context_data方法创建用于呈现模板的上下文字典。使用 get_form_kwargs如果你想将额外的 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

关于 Django : Add kwargs parameters from get_context_data() to ModelForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53193582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com