当我尝试编辑这个对象时,我收到上述错误。 如果我使用表单中所需的值创建一个dict,它只会保存一个新对象,而不会覆盖当前的对象。
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'
答案 0 :(得分:3)
您应该为POST请求和GET请求设置instance
。
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():
...
您不需要为POST请求设置initial
,因此我已将其删除。
答案 1 :(得分:1)
尝试:
if request.method == 'POST':
form = SongForm(request.POST)
if form.is_valid():
obj = form.save()
return HttpResponseRedirect('/music-manager/song/' + str(obj.pk))