Get Primary Key after Saving a ModelForm in Django

后端 未结 2 1858
萌比男神i
萌比男神i 2020-12-13 23:45

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 requi

相关标签:
2条回答
  • 2020-12-14 00:19

    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()
    
    0 讨论(0)
  • 2020-12-14 00:28

    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

    0 讨论(0)
提交回复
热议问题