1

我正在尝试使用我的 Django FormWizard 编辑现有对象。我正在遵循此博客文章中描述的技术,但它不起作用。这是我的编辑视图:

@login_required
def edit_wizard(request, id):
    thing = get_object_or_404(Thing, pk=id)
    if thing.user != request.user:
        raise HttpResponseForbidden()
    else:
        initial = {0: {'year': thing.year,
                       'make': thing.make,
                       'series': thing.series,
                        ....etc.
                       },
                   1: {'condition': thing.condition,
                        ....etc.
                       },
                   }

     form = CreateWizard.as_view([StepOneForm, StepTwoForm, StepThreeForm], initial_dict=initial)
     return form(context=RequestContext(request), request=request)

你能帮我弄清楚如何向向导提供初始数据,以便我可以允许用户编辑他们的对象吗?谢谢你的想法!


编辑:(2/18/13)

得到一个:

TypeError at /edit/10/   __init__() takes exactly 1 argument (3 given)

@sneawo 在下面的回答解决了这个问题,但仍然没有传递初始数据,而是向导创建了新对象。


编辑:(2/19/13)

class CreateWizard(SessionWizardView):
    file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT))
    def done(self, form_list, **kwargs):
        instance = Thing()
        for form in form_list:
            for field, value in form.cleaned_data.iteritems():
                setattr(instance, field, value)
        instance.user = self.request.user
        instance.save()
        return render_to_response('wizard-done.html', {
            'form_data': [form.cleaned_data for form in form_list],
        })
4

2 回答 2

2

根据文档,对于 Django 1.4+,您在initial_dict关键字参数中传递初始数据。对于以前的版本(1.3,它似乎在 1.3 之前不存在),关键字参数是initial。此外,初始数据字典中步骤的键应该是字符串而不是整数。

initial = {'0': {'year': thing.year,
                 'make': thing.make,
                 'series': thing.series,
                  ....etc.
                },
           '1': {'condition': thing.condition,
                  ....etc.
                },
          }

更新:要更新同一个对象,您还必须设置 id,否则 django 无法知道要更新哪个对象。一种简单的方法是在隐藏字段中传递 id,但您必须在 (done) 方法中再次进行用户权限检查。

initial = {0: {'id': thing.id,


class CreateWizard(SessionWizardView):
    file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT))
    def done(self, form_list, **kwargs):
       id = form_list[0].cleaned_data['id']
       thing = get_object_or_404(Thing, pk=id)
       if thing.user != self.request.user:
           raise HttpResponseForbidden()
       else:
         instance = Thing()
         for form in form_list:
             for field, value in form.cleaned_data.iteritems():
                 setattr(instance, field, value)
         instance.user = self.request.user
         instance.save()
         return render_to_response('wizard-done.html', {
             'form_data': [form.cleaned_data for form in form_list],})

当然 StepOneForm 应该有隐藏字段的 id:

class StepOneForm(forms.Form):
    id = forms.IntegerField(widget=forms.HiddenInput)
于 2013-02-21T16:47:38.727 回答
1

尝试使用form = CreateWizard.as_view([StepOneForm, StepTwoForm, StepThreeForm], initial=initial)

于 2013-02-19T22:56:07.440 回答