0

这是这个问题的延续。

问题是代码不允许创建新对象,因为thing = get_object_or_404(Thing, pk=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],})

如何使用get_or_create此功能?还是有另一种更好的方法在这个函数中创建新对象?谢谢你的想法!

4

1 回答 1

0

一种方法是:

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']

       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:
               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],})
于 2013-07-03T17:30:59.613 回答