2017-04-14 30 views
0

這裏之前引用/ create_playlist /局部變量「播放列表」是我的views.py:UnboundLocalError在分配

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,}) 

我有Playlist模型,並forms.py其中包含了播放列表model.I的各個領域要用戶可以創建自己的播放列表,併爲我做了這個,但是當我編譯它,它給了我這個錯誤:

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」對象有沒有屬性‘名’

這裏是我的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' ] 
+0

''playlist'範圍if'和你外面使用它。如果'if'語句不滿足,這個錯誤可能會發生 – kuro

回答

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不是已知的語法。

+0

感謝隊友,它的工作。但是當我點擊提交,它返回:'WSGIRequest'對象沒有屬性'名稱' – blacklight

+1

你是如何傳遞這個'名稱'風景? – AKS

+1

你添加的是表單和模型。它仍然沒有告訴我們爲什麼當你已經使用表單時你會使用'request.name'。 – AKS

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,}) 
+0

感謝隊友,它工作。但是當我點擊提交時,它會返回:'WSGIRequest'對象沒有屬性'name' – blacklight

相關問題