samuelbeard
samuelbeard

Reputation: 41

'MyModel' object is not iterable when saving object (Django)

When I try to edit this an object, I get the above error. If I create an dict with the values required in the form, it just saves a new object and doesn't overwrite the current one.

views.py

@login_required
def edit_song(request, song_id):
    song = get_object_or_404(Song, pk=song_id)

    form = SongForm(instance=Song.objects.get(id=song_id))

    if request.method == 'POST':
        form = SongForm(data=request.POST, initial=song)
        if form.is_valid():
            obj = form.save()

            obj.save()
            return HttpResponseRedirect('/music-manager/song/' + str(obj.pk))

forms.py

class SongForm(forms.ModelForm):
    class Meta:
        model = Song
        fields = ['title', 'lyrics', 'notes', 'key', 'chords', 'video', 'audio']

    def __init__(self, *args, **kwargs):
        super(SongForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'

Upvotes: 1

Views: 431

Answers (2)

Alasdair
Alasdair

Reputation: 308999

You should set instance for POST requests as well as GET requests.

song = get_object_or_404(Song, pk=song_id)
form = SongForm(instance=song)

if request.method == 'POST':
    form = SongForm(data=request.POST, instance=song)
    if form.is_valid():
        ...

You don't need to set initial for POST requests, so I've removed that.

Upvotes: 3

Chiefir
Chiefir

Reputation: 2671

Try:

if request.method == 'POST':
    form = SongForm(request.POST)
    if form.is_valid():
        obj = form.save()
        return HttpResponseRedirect('/music-manager/song/' + str(obj.pk))

Upvotes: 1

Related Questions