我在下面有以下观点。我想使用' email
'从get_context_data method
预先填充UserAuthenticationForm表单中的表单字段,这怎么可能?
查看:
class CampaignLoginView(LoginView):
model = Campaign
form_class = UserAuthenticationForm
def get_context_data(self, *args, **kwargs):
context = super(CampaignLoginView, self).get_context_data(*args, **kwargs)
user = AppUser.objects.get(pk=1)
context['email'] = user.email
形式:
class UserAuthenticationForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super(UserAuthenticationForm, self).__init__(*args, **kwargs)
或者是否有办法'我应该这样做?
答案 0 :(得分:2)
您要做的是将initial
数据传递给表单。假设LoginView是一个包含FormMixin的基于类的视图,最好用get_form_kwargs
方法完成:
def get_form_kwargs(self):
kwargs = super(CampaignLoginView, self).get_form_kwargs()
kwargs['initial']['email'] = self.request.user.email
return kwargs