Django表单向导:访问表单中的上下文

时间:2014-09-11 08:12:15

标签: django forms wizard django-context

我有一个包含5个表单的Django 1.6表单向导。我希望每个表单都可以访问以前所有表单中字段的值。

我在views.py中定义了一个get_context_data方法,它似乎做了它应该做的事情。这是我的views.py

from django.shortcuts import render
from django.shortcuts import render_to_response
from django.contrib.formtools.wizard.views import SessionWizardView
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
import pdb

class CalcWizard(SessionWizardView):

    # Override template_name
    template_name = 'calc/forms.html'

    # Define a __name__ property on the wizard.
    # We do this because a number of Django decorators
    # raise an AttributeError when you use them to 
    # decorate an instance, complaining they cant find __name__
    @property
    def __name__(self):
        return self.__class__.__name__

    def get_context_data(self, form, **kwargs):
        context = super(CalcWizard, self).get_context_data(form=form, **kwargs)
        if self.steps.current >= 0:
            data_0 = self.get_cleaned_data_for_step('0') # zero indexed
            context.update({'data_0':data_0})
        if self.steps.current >= 1:
            data_1 = self.get_cleaned_data_for_step('1')
            context.update({'data_1':data_1})
        if self.steps.current >= 2:
            data_2 = self.get_cleaned_data_for_step('2')
            context.update({'data_2':data_2})
        return context

    def done(self, form_list, **kwargs):
        # This is not done yet
        return render_to_response('calc/forms.html', {
            'form_data': [form.cleaned_data for form in form_list],
        })

但是,我不明白如何访问表单中的上下文数据。

这是我的forms.py:

的一部分
class DeliveryForm(forms.Form):

    costs = forms.DecimalField(\
        max_digits=16, \
        decimal_places=2, \
        label=_(u'Materialkostnad (kr)'), \
        localize=True, \
        validators=[MinValueValidator(0)])
    amount = forms.DecimalField(\
        max_digits=16, \
        decimal_places=2, \
        label=_(u'Mängd/Antal (kvm)'), \
        localize=True, \
        validators=[MinValueValidator(0)])
    CHOICES=[(0,'BLC inomhus'), (1,'BLC utomhus'), \
        (2,'BLC externt inomhus'), (3,'BLC externt utomhus')]
    blc_inventory = forms.ChoiceField(\
        choices=CHOICES, \
        widget=forms.RadioSelect(), \
        label=_(u'Var vill du lagra ditt material?'))
    ...
    ...
    ...
    ...

    def __init__(self, *args, **kwargs):
        super(DeliveryForm, self).__init__(*args, **kwargs)
        if kwargs ??? is not None:
            form.costs=???

以下是我的urls.py

的部分内容
urlpatterns = patterns('',

    url(r'^admin/filebrowser/', include(site.urls)),
    url(r'^grappelli/', include('grappelli.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^calc/$', CalcWizard.as_view([\
        ConstructionForm,\
        DeliveryForm,\
        KitningForm,\
        CarryinginForm,\
        ResultForm]
    )),
)

如何访问表单中的上下文数据?

1 个答案:

答案 0 :(得分:0)

你的描述有点简短,但我假设你在视图中看到了get_context_data ,因为你说它做了它应该做的事情。

只有在具有上下文的视图中实例化表单后,您的表单才能访问此上下文。因此,您可以将上下文传递给您的表单,如:

form = DeliveryForm(ctx=context)

在您的表单__init__中,您可以检查它是否可以像这样使用:

def __init__(self, *args, **kwargs):
    super(DeliveryForm, self).__init__(*args, **kwargs)
    ctx = kwargs.get('ctx', None)
    if ctx is not None:
        form.s_costs=ctx['costs']

如果视图使用了向导之类的内容,则可以使用get_form_kwargs为表单设置正确的上下文。喜欢的东西:

def get_form_kwargs(self, step):
    kwargs = {}
    if step == 1:
        kwargs['foo'] = 'bar'
    return kwargs

您可以从表单中访问kwarg['foo']