/ create_playlist / local变量'播放列表中的UnboundLocalError'在转让之前引用

时间:2017-04-14 05:53:51

标签: python html django forms exception

这是我的views.py:

def create_playlist(request):
    form = PlaylistForm(request.POST or None)
    if form.is_valid():
        playlist = form.save(commit=False)
        playlist.name = request.name
        context={
            'playlist':playlist,
            'name':playlist_name,
        }

        return render(request, 'create_playlist.html', context)
    playlist.save()

    context = {
            "form": form,
        }
    return render(request, 'create_playlist.html', {'form': form,})

我有一个Playlistforms.py的模型,其中包含播放列表模型的所有字段。我希望用户能够创建自己的播放列表,为此我创建了这个但是当我编译时它,它给出了我的错误:

UnboundLocalError at /create_playlist/
local variable 'playlist' referenced before assignment
Request Method: GET
Request URL:    http://localhost:8000/create_playlist/
Django Version: 1.9.6
Exception Type: UnboundLocalError
Exception Value:    
local variable 'playlist' referenced before assignment

编辑:WSGIRequest'对象没有属性' name'

这是我的models.py

class Playlist(models.Model):
    name = models.CharField(max_length=200, null=False, blank=False,default='')
    songs = models.ManyToManyField('Song')
    def __str__(self):
        return self.name

这是我的forms.py:

class PlaylistForm(forms.ModelForm):
    class Meta:
        model=Playlist
        fields = ['name', 'songs' ]

2 个答案:

答案 0 :(得分:0)

由于以下行,您收到错误。它在if form.is_valid():块之外:

playlist.save()

我认为您希望将其放在if块内,并在使用render返回回复之前:

if form.is_valid():
    playlist = form.save(commit=False)
    playlist.name = request.name
    playlist.save()
    context={
        'playlist':playlist,
        'name':playlist_name,
    }

    return render(request, 'create_playlist.html', context)

另外,请注意request.name不是已知语法。

答案 1 :(得分:0)

如果表单无效,则不会定义playlist

这样做:

def create_playlist(request):
    form = PlaylistForm(request.POST or None)
    if form.is_valid():
        playlist = form.save(commit=False)
        playlist.name = request.name
        playlist.save()
        context={
            'playlist':playlist,
            'name':playlist_name,
        }
        return render(request, 'create_playlist.html', context)
    context = {
        "form": form,
    }
    return render(request, 'create_playlist.html', {'form': form,})