Note that there are some explanatory texts on larger screens.

plurals
  1. POIn Django, how can I pre-populate an edit form from a model/child, but save submission as new instance?
    text
    copied!<p>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.</p> <p>Example Model:</p> <pre><code>class Artist(models.Model): artist = models.CharField(max_length=100) class Song(models.Model): artist = models.ForeignKey(Artist) song = models.CharField(max_length=200) </code></pre> <p>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.</p> <p>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.</p> <p>Example View:</p> <pre><code>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}) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload