python - Django: Updating Object in Forms with Custom Save Method -
this continuation of this question, in learned how over-ride save method of multi-step formwizard save form fields differently in different forms. @yuji tomita's help, figured out how save forms correctly. @ point, however, lost on how update instance , save changes object.
i have tried follow logic learned @yuji, have not been able update object.
this am:
class steponeform(forms.form): ... def save(self, thing): field, value in self.cleaned_data.items(): setattr(thing, field, value) class steptwoform(forms.form): ... def save(self, thing): 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] field, value in self.cleaned_data.items(): setattr(thing, field, value) here how have over-written wizard's done method save instances:
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 , thing.user != self.request.user: raise httpresponseforbidden() if not thing: instance = thing() 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 form in form_list],}) how should change save method can update thing instance? ideas!
edit: adding view edits object:
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 populate initial_dict instance }, '1': {image': thing.main_image, ... }, '2': {description': thing.additional_description, 'latitude': thing.point.latitude, #thing has foreign key point records lat , lon 'longitude': thing.point.longitude, }, } form = mywizard.as_view([steponeform, steptwoform, stepthreeform], initial_dict=initial) return form(context=requestcontext(request), request=request)
what problem seeing? error or object not saved?
probably indentation in done() method not correct, not calling form.save(). should :
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 moved out of if 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 form in form_list],})
Comments
Post a Comment