Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Primary Key after Saving a ModelForm in Django

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() 
like image 251
Matt Avatar asked Apr 09 '09 05:04

Matt


People also ask

How do I refer primary key in Django?

If you'd like to specify a custom primary key, specify primary_key=True on one of your fields. If Django sees you've explicitly set Field.primary_key , it won't add the automatic id column. Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).

What does save () do in Django?

save() method can be used to insert new record and update existing record and generally used for saving instance of single record(row in mysql) in database.


2 Answers

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() 
like image 102
monkut Avatar answered Sep 19 '22 07:09

monkut


In the case where you have set form.save(commit=False) because you want to modify data and you have a many-to-many relation, then the answer is a little bit different:

def contact_create(request):     if request.method == 'POST':         form = ContactForm(request.POST)         if form.is_valid():             new_contact = form.save(commit=False)             new_contact.data1 = "gets modified"             new_contact.save()             form.save_m2m()             return HttpResponseRedirect(reverse(contact_details, args=(new_contact.pk,)))     else:         form = ContactFrom() 

https://docs.djangoproject.com/en/1.3/topics/forms/modelforms/#the-save-method

like image 40
Kevin Avatar answered Sep 19 '22 07:09

Kevin