views:

82

answers:

1

Hi

I have a complex django object, which has properties of other class types. This gets like this:

class Order:
   contractor - type Person
   some other fields....

In my form I'd like to be able to either choose existing Person object from the dropdown or add a new one with a form. I've managed to create forms and appropriate workflow, but the problem is with saving the Order itself, I simply can't get the id of a saved Person instance. I'm doing sth like this:

def make_order(request):
  if request.method == 'POST':
    parameters = copy.copy(request.POST)
    contractor_form = ContractorForm(parameters)
    if contractor_form.is_valid():
      contractor_form.save()
      parameters['contractor'] = ???
    form = OrderForm(parameters)
    if form.is_valid():
      form.save() 
      return HttpResponseRedirect('/orders/')
  else:
    form = OrderForm()
    contractor_form = ContractorForm()

  return render_to_response('orders/make_order.html', {'order_form' : form, 'contractor_form' : contractor_form})

So, if POST request reaches this method I first check if ContractorForm have been filled - I assume that if the form is valid, it is meant to be used. If yes, than I save it and would like to assign the saved object's database id to appropriate field for OrderForm to find it.

All my forms are ModelForms.

The questions are:

  1. Are there better ways to do this? (choose from dropdown or add in place) - better or more pythonic ;-)
  2. How can I get saved objects id when using ModelForms?

Edited

My ContractorForm is:

class ContractorForm(ModelForm):
  class Meta:
    model = Contractor

Nothing fancy.

+1  A: 
rebus
This was my first guess, but unfortunately it doesn't work like this. ModelForm.save() returns None. There should be a way of doing this with overloaded save() method, but this seems overcomplicated and messy.
Marcin Cylke
Can you show us your `contractor` ModelForm code then?
rebus
Well, I've tested this again, and your solution works. I'll however test it more thoroughly with my specific case.
Marcin Cylke