2016-10-22 37 views
0

我有一個通過POST方法將數據發送到視圖的表單。我的問題是,我不能在deleteview中訪問表單的發佈數據。在歌曲被刪除後,我希望用戶被髮回到歌曲所屬的專輯詳情頁面。是如下所示我的代碼:Django:如何在刪除視圖中使用request.POST

形式(內部album_detail.html):

<form action="{% url 'music:delete-song' pk=song.pk album_id=song.album_id %}" method="POST"> 
    {% csrf_token %} 
<input type="hidden" name="album_id" value="{{ song.album_id }}" /> 
<button type="submit" class="btn btn-danger btn-xs" role="button">Delete</button> 
</form> 

的urls.py:

#---- 
app_name = 'music' 
urlpatterns = [ 
    #---- 
    url(r'^album/(?P<pk>[0-9]+)/detail/$', views.AlbumDetail.as_view(), name='album-detail'), 
    url(r'^song/(?P<pk>[0-9]+)/delete/(?P<album_id>[0-9]+)/$', views.SongDelete.as_view(), name='delete-song'), 
] 

最後的視圖:

class SongDelete(DeleteView): 
    model = Song 
    album_id = request.POST.get('album_id') 
    success_url = reverse_lazy('music:album-detail', kwargs={'pk': album_id}) 

album_id不能像上面那樣設置。如何將表單中的album_id設置爲發佈數據album_id,以便將用戶發送回相冊詳細信息URL?

回答

0

通過實現你的意見當然get_success_url

def get_success_url(self): 
    album_id = self.request.POST.get('album_id') # Do something else if it's missing? 
    return reverse( # no need for lazy here 
     'music:album-detail', 
     kwargs={'pk': album_id} 
    ) 
+0

剛加入自我要求和它的工作!我還沒有測試@ cutteeth的答案,但我發現這一點很簡單。謝謝你們 –

1

你必須重寫delete() and get_success_url()

def delete(self, request, *args, **kwargs): 
    self.object = self.get_object() 
    self.album = self.object.album # assuming that song have a foreignkey reference to album model 
    self.object.delete() 
    success_url = self.get_success_url() 
    return HttpResponseRedirect(success_url) 


def get_success_url(self): 
    album = self.album  
    return reverse( 
     'music:album-detail', 
     kwargs={'pk': album.id} 
     ) 

success_url is obtained from get_success_url()方法和方法是從delete()調用。您可以使用類似於

def get_success_url(self): 
    return `/album/details/' + str(self.album.id) 

使其更簡單。或者你可以在delete方法中提供redirect_url目錄。

def delete(self, request, *args, **kwargs): 
    self.object = self.get_object() 
    self.album = self.object.album # assuming that song have a foreignkey reference to album model 
    self.object.delete() 
    return HttpResponseRedirect('/album/details/' + str(self.album.id)) 

參考this link得到幫助基於類視圖