我有一个表单通过POST方法将数据发送到视图。我的问题是我无法在deleteview中访问表单的帖子数据。删除歌曲后,我希望将用户发送回歌曲所属的专辑详细信息页面。我的代码如下所示:
表格(在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 :(得分: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以获取有关基于班级的观点的帮助
答案 1 :(得分: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}
)