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:
- Are there better ways to do this? (choose from dropdown or add in place) – better or more pythonic 😉
- How can I get saved objects id when using ModelForms?
Edited
My ContractorForm is:
class ContractorForm(ModelForm):
class Meta:
model = Contractor
Nothing fancy.
save() should return the newly created instance.
where id would be
instance.id, or even betterinstance.pk.pkvs.id:Follow-up on comment:
Well it does work by default, so there must be something else wrong.
models.py
forms.py
Test in shell: