在 Django 中保存 ModelForm 后获取主键 [英] Get Primary Key after Saving a ModelForm in Django
本文介绍了在 Django 中保存 ModelForm 后获取主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在保存 ModelForm 后获取主键?表单经过验证并保存后,我想将用户重定向到需要联系人主键的 contact_details 视图.
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()
推荐答案
The ModelForm's save method returns the saved object.
试试这个:
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()
这篇关于在 Django 中保存 ModelForm 后获取主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文