Django如何使用参数形式上下文预填充表单字段

时间:2014-06-11 19:32:12

标签: python django django-forms

我在下面有以下观点。我想使用' 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)

或者是否有办法'我应该这样做?

1 个答案:

答案 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