Post Request not available inside get_queryset function inside ListView

大憨熊 提交于 2021-02-05 11:46:52

问题


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.

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):
    ....

回答1:


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

Look Django's View source to check how allowed methods defined.



来源:https://stackoverflow.com/questions/50055999/post-request-not-available-inside-get-queryset-function-inside-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!