I'm trying to prepopulate a ModelForm and an inlineformset_factory with an instance of a Model, BUT when the user submits the form, I need to create a new instance of the Model and it's related child records.
Example Model:
class Artist(models.Model):
artist = models.CharField(max_length=100)
class Song(models.Model):
artist = models.ForeignKey(Artist)
song = models.CharField(max_length=200)
I want the user to see an edit form based on an instance of Artist, along with an InlineFormSet for that Artist's related Songs. The form will be prepopulated with the existing data and the user can change the artist's name and the song names. However, when the user submits the form, I don't want to overwrite the existing records. Instead, I want to create a new instance of Artist and add new Songs for this new artist.
I have tried setting the primary key of artist to None before saving - and this forces a new instance of Artist. However, I lose the ForeignKey relationship between Artists and Songs.
Example View:
def edit(request, artist_id=None):
if artist_id == None:
artistsubmission = Artist()
else:
artistsubmission = Artist.objects.get(id = artist_id)
artistsubmission.pk = None
if request.method == 'POST':
form = ArtistEditForm(request.POST, instance=artistsubmission)
formset = SongFormSet(request.POST, instance=artistsubmission)
if form.is_valid() and formset.is_valid():
form.save()
formset.save()
return HttpResponseRedirect('/success/')
else:
form = ArtistEditForm(instance=artistsubmission)
formset = SongFormSet(instance=artistsubmission)
return render_to_response('edit.html', {'form':form, 'formset':formset})