views:

509

answers:

1

How do I get the primary key after saving a ModelForm? After the form has been validated and saved, I would like to redirect the user to the contact_details view which requires the primary key of the contact.

def contact_create(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse(contact_details, args=(form.pk,)))
    else:
        form = ContactForm()
+5  A: 

The ModelForm's save method returns the saved object.

Try this:

def contact_create(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            new_contact = form.save()
            return HttpResponseRedirect(reverse(contact_details, args=(new_contact.pk,)))
    else:
        form = ContactForm()
monkut
Thank you very much!
Matt
No problem, that's easily overlooked and not immediatly intuitive. ;)
monkut