Question

This is a continuation of this question.

The problem is that the code does not allow for creating new objects because of 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],})

How can I use get_or_create with this function? Or is there another, better way to create new objects within this function? Thanks for your ideas!

Was it helpful?

Solution

One way to do it would be:

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],})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top