Django:使用自定义保存方法更新表单中的对象

时间:2013-10-07 19:36:49

标签: python django forms save instance

这是this question的延续,我在其中学习了如何覆盖多步骤向导的save方法,以不同的形式保存表单字段。感谢@Yuji Tomita的帮助,我想出了如何正确保存表单。但是,在这一点上,我对如何更新实例并保存对象的更改感到迷茫。

我试图遵循从@Yuji学到的逻辑,但未能正确更新对象。

这就是我所在的地方:

class StepOneForm(forms.Form):
     ...
     def save(self, thing):
        for field, value in self.cleaned_data.items():
            setattr(thing, field, value)

class StepTwoForm(forms.Form):
     ...
     def save(self, thing):
        for field, value in self.cleaned_data.items():
            setattr(thing, field, value)

class StepThreeForm(forms.Form):
     ...
     def save(self, thing):
         thing.point = Point.objects.get_or_create(latitude=self.cleaned_data.get('latitude'), longitude=self.cleaned_data.get('longitude'))[0]
         for field, value in self.cleaned_data.items():
             setattr(thing, field, value)

以下是我如何覆盖向导的done方法来保存实例:

class MyWizard(SessionWizardView):
    file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT))
    def done(self, form_list, **kwargs):
        id = form_list[0].cleaned_data['id']
        try:
            thing = Thing.objects.get(pk=id)
            instance = thing
        except:
            thing = None
            instance = None
        if thing and thing.user != self.request.user:
            raise HttpResponseForbidden()
        if not thing:
            instance = Thing()
            for form in form_list:
                form.save(instance)
            instance.user = self.request.user
            instance.save()
        return render_to_response('wizard-done.html', {
                'form_data': [form.cleaned_data for form in form_list],})

我应该如何更改save方法,以便我可以正确更新thing实例?谢谢你的想法!


编辑:添加编辑对象的视图:

def edit_wizard(request, id):
    thing = get_object_or_404(Thing, pk=id)
    if thing.user != request.user:
        raise HttpResponseForbidden()
    else:
        initial = {'0': {'id': thing.id,
                       'year': thing.year,
                       'color': thing.color,
                       ... #listing form fields individually to populate the initial_dict for the instance
                       },
                   '1': {image': thing.main_image,
                       ...
                       },
                   '2': {description': thing.additional_description,
                       'latitude': thing.point.latitude,  #thing has a foreign key to point that records lat and lon
                       'longitude': thing.point.longitude,
                       },
                    }

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

1 个答案:

答案 0 :(得分:1)

您看到的问题是什么?获取错误或对象未保存?

done()方法中的缩进可能不正确,因此不会调用form.save()。应该是这样的:

class MyWizard(SessionWizardView):
    file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT))
    def done(self, form_list, **kwargs):
        ... 
        #existing code

        if not thing:
            instance = Thing()

        #this is moved out of if
        for form in form_list:
            form.save(instance)

        instance.user = self.request.user
        instance.save()
        return render_to_response('wizard-done.html', {
                'form_data': [form.cleaned_data for form in form_list],})