2013-07-03 2 views
0

이것은 계속됩니다 this question입니다.get_or_create 사용 Django

문제는 코드 때문에 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를 사용할 수있는 새로운 객체를 생성을 허용하지 않는다는 것입니다? 아니면이 함수 내에서 새로운 객체를 만드는 다른 방법이 있습니까? 당신의 아이디어에 감사드립니다!

답변

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],}) 
+0

덕분에이 완벽! –