How to get /test/?grid-view or /test/?list-view' in Django view

落爺英雄遲暮 提交于 2019-12-12 01:42:32

问题


I have a page that can be viewed by list or grid view through jQuery, but I want the URL to display what view it is -- especially when user paginate so that they don't have to reclick what they want to view -- so something like this: /test/?grid_view or /test/?list_view.

I've been trying to use request.GET.get, but it doesn't seem to be working. Here is what I have so far:

def test (request):
    grid_view = request.GET.get('grid_view')
    list_view = request.GET.get('list_view')
    if grid_view:
        return render_to_response('grid_view.html', {}, context_instance=RequestContext(request))
    elif list_view:
        return render_to_response('list_view.html', {}, context_instance=RequestContext(request))
    else:
        return render_to_response('default_view.html', {}, context_instance=RequestContext(request))

Then in my main template I'd point the different views to <a href="/?list_view/">list view</a>, etc. There is probably a better way to do it so any suggestions are appreciated too.


回答1:


An empty string is evaluated to False and, that is what your GET request Query String parameters will contain.

You could modify your code to:

if 'grid_view' in request.GET or 'grid_view/' in request.GET:
    pass
elif 'list_view' in request.GET or 'list_view/' in request.GET:
    pass

Or:

if request.GET.has_key('grid_view') or request.GET.has_key('grid_view/'):
# ...



回答2:


That's not a GET parameter. Use request.META['QUERY_STRING'] to get the query string.



来源:https://stackoverflow.com/questions/10662391/how-to-get-test-grid-view-or-test-list-view-in-django-view

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