如何在保存ModelForm后获取主键?在验证并保存表单后,我想将用户重定向到contact_details视图,该视图需要联系人的主键。
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()
答案 0 :(得分:51)
试试这个:
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()
答案 1 :(得分:10)
如果您设置了form.save(commit = False),因为您想要修改数据并且您有多对多的关系,那么答案会有所不同:
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