Peter O Peter O - 4 months ago 38
Python Question

Django: How to use request.POST in a delete view

I have a form sending data to a view via POST method. My problem is that I cant access the form's post data in the deleteview. After the song is deleted, I want the user to be sent back to the album-detail page to which the song belongs. My code is as shown below:

The form (inside album_detail.html):

<form action="{% url 'music:delete-song' 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>


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

And finally the view:

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

The album_id can not be set as above. How can I set the album_id to the post data album_id from the form, so that the user is sent back to the album-detail URL?


By implementing your views get_success_url of course:

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
         kwargs={'pk': album_id}