4

According to the form wizard docs, the initial data should be a static dict. But is it possible to provide initial data dynamically?

Here is my situation:

 def get_context_data(self, form, **kwargs):
    context = super(debugRegistrationWizard, self).get_context_data(form=form, **kwargs)
    email = InvitationKey.objects.get_key_email(self.kwargs['invitation_key'])
    context.update({'invitation_key': self.kwargs['invitation_key']})
    return context

The email is what I want for initial data in step0, but I can only get this email in get_context_data method. How can I do that?

By the way: if the urlconf for formwizard.as_view accept argument like:

url(r'^registration/(?P<invitation_key>\w+)$', debugRegistrationWizard.as_view(FORMS)),

does it mean I have to pass a variable to my form's action attributes, because otherwise when I submit the form, I will get a not found url error.

4

2 回答 2

6

您可以覆盖该方法get_form_initial

def get_form_initial(self, step):
    initial = self.initial_dict.get(step, {})
    if step == 42:
        email = InvitationKey.objects.get_key_email(self.kwargs['invitation_key'])
        initial.update({'email': email})
    return initial

参考:https ://django-formtools.readthedocs.io/en/latest/wizard.html#formtools.wizard.views.WizardView.get_form_initial

于 2013-05-11T07:24:50.863 回答
3

一个答案几乎就在那里。您确实需要覆盖get_form_initial,但self.kwargs(至少在最新版本的 Django formtools 中)不包含请求的 GET 或 POST 参数。

解决方案非常简单:只需直接引用请求中的值,因为self.request它是向导上的一个属性。

def get_form_initial(self, step):
    initial = self.initial_dict.get(step, {})
    invitation_key = self.request.GET.get("invitiation_key")
    email = InvitationKey.objects.get_key_email(invitation_key)
    initial.update({'email': email})
    return initial
于 2015-12-04T02:07:27.160 回答