问题描述
在ListView中,我可以轻松地使用 def post(自己,请求)方法从列表视图中进行发布请求.但是我想从 def get_queryset(self)发出发帖请求,而我现在还不能这样做.当我尝试执行此操作时,即使通过 http_method_names 允许发布方法,它也会显示" 405方法不允许!".
In ListView, I can easily use def post(self, request) method to make a post request from a list view. But I want to make the post request from def get_queryset(self) which I am not yet able to do. When I try to do it it shows "method 405 not allowed!" even though post method is allowed through http_method_names.
如何在 get_queryset 功能内访问POST请求?
How can I access POST request inside get_queryset function?
class ZonListView(SearchMixin, SingleTableMixin, ListView):
template_name = 'cadmin/list.html'
model = Zon
table_class = ZonTable
search_fields = {
'title': 'icontains',
'description': 'icontains',
}
def post(self, request): # ***** this one works! ******
try:
toggle_status = request.POST.get('toggle-status')
pk = int(request.POST.get('pk'))
....
return HttpResponseRedirect(reverse('cadmin:zon_list'))
def get_queryset(self):
qs = super(ZonListView, self).get_queryset()
if self.request.POST: #***** Not working. 405 Error *****#
try:
toggle_status = self.request.POST.get('toggle-status')
pk = int(self.request.POST.get('pk'))
......
if self.request.GET:
try:
status = self.request.GET.get('status')
qs = qs.filter(status=status)
except Exception:
pass
return qs.distinct()
def get_context_data(self, **kwargs):
....
推荐答案
要使方法允许,您需要实现与方法相同的功能,请以您的情况为准.因此,要在get queryset中使用 request.POST
,您还需要定义 post()
方法,如下所示:
To make method allowed you need to implement function named same as method, post in your case. So to use request.POST
in get queryset you also need to define post()
method like this:
def post(self, request): # ***** this method required! ******
self.object_list = self.get_queryset()
return HttpResponseRedirect(reverse('cadmin:zon_list'))
def get_queryset(self):
qs = super(ZonListView, self).get_queryset()
if self.request.POST: #***** Now allowed *****#
try:
toggle_status = self.request.POST.get('toggle-status')
pk = int(self.request.POST.get('pk'))
......
查看Django的 View
源,以检查允许的方法的定义方式.
Look Django's View
source to check how allowed methods defined.
这篇关于Post Request在ListView的get_queryset函数内部不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!