I am trying to pre-populate ModelForm and inlineformset_factory with a model instance, BUT, when the user submits the form, I need to create a new model instance and related child records.
Model Example:
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 editing form based on an instance of Artist, as well as an InlineFormSet for these artist related songs. The form will be pre-filled with existing data, and the user can change the artist name and song names. However, when the user submits the form, I do not want to overwrite existing entries. Instead, I want to create a new instance of Artist and add new songs for this new artist.
I tried to set the primary key of the artist to None before saving - and this forces a new instance of Artist. However, I am losing the ForeignKey relationship between Artists and Songs.
Example:
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})
user90419
source share