1
In this case I wouldn’t use a formset at all. If you need to collect user information to create the new listing, use a single ListingForm
and AddressForm
, save the new address, and then save the ListingForm
with commit=False
, assign the user and address to it, and then save the instance.
@login_required(login_url='share:login_view', redirect_field_name='share:addlisting')
def addlisting(request):
if request.method == 'POST':
address_form = AddressForm(request.POST, prefix="address")
listing_form = ListingForm(request.POST, prefix="listing")
if address_form.is_valid() and listing_form.is_valid():
new_address = address_form.save()
new_listing = listing_form.save(commit=False)
new_listing.address = new_address
new_listing.user = request.user
new_listing.save()
return HttpResponseRedirect(reverse('/listing_added/'))
else:
address_form = AddressForm(prefix="address")
listing_form = ListingForm(prefix="listing")
return render(request, 'share/addlisting.html', {
"address_form": address_form,
"listing_form": listing_form
})
If you ever have a many-to-many relationship on Listings
you’ll need to explicitly save those after saving the instance, as discussed here:
https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#the-save-method
Source:stackexchange.com