'save() prohibited to prevent data loss due to unsaved related object

I need to pass a primary key from a newly created ModelForm to another form field in the same view but I get an error. Any suggestions to make this work? It looks like in the past, this would be the answer:

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()

From the documentation, this is what is happening in the newer Django version > 1.8.3

p3 = Place(name='Demon Dogs', address='944 W. Fullerton') Restaurant.objects.create(place=p3, serves_hot_dogs=True, serves_pizza=False)
Traceback (most recent call last):
...
ValueError: save() prohibited to prevent data loss due to unsaved related object 'place'.

This is how I am getting my pk from the view:

my_id = ""
if form.is_valid():
    # deal with form first to get id
    model_instance = form.save(commit=False)
    model_instance.pub_date= timezone.now()
    model_instance.user= current_user.id
    model_instance.save()
    my_id = model_instance.pk

if hourformset.is_valid():
    hourformset.save(commit=False)
    for product in hourformset:
        if product.is_valid():
            product.save(commit=False)
            product.company =  my_id
            product.save()
else:
    print(" modelform not saved")
return HttpResponseRedirect('/bizprofile/success')


Solution 1:[1]

it is simple:

p3 = Place(name='Demon Dogs', address='944 W. Fullerton')   
p3.save() # <--- you need to save the instance first, and then assign
Restaurant.objects.create(
    place=p3, serves_hot_dogs=True, serves_pizza=False
) 

Solution 2:[2]

Answered - The problem arose from django not saving empty or unchanged forms. This led to null fields on those unsaved forms. Problem was fixed by allowing null fields on foreign keys, as a matter of fact -- all fields. That way, empty or unchanged forms did not return any errors on save.

FYI: Refer to @wolendranh answer.

Solution 3:[3]

I just removed my model.save() and the error went away.


This only works if you are saving it when there are no changes. Otherwise you should save it one time, if you changed something in the queryset.

an example:

views.py

queryset = myModel.objects.get(name="someName", value=4)

queryset.value = 5
# here you need to save it, if you want to keep the changes.
queryset.save()
...

# If you save it again, without any changes, for me I got the error save() prohibited to prevent data loss due to unsaved related object

# don't save it again, unless you have changes.
# queryset.save()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 doniyor
Solution 2
Solution 3 AnonymousUser