获取Self.Kwargs中不可用的变量

时间:2014-05-22 12:55:55

标签: python django django-views

我有以下代码。我试图传递一个名为' sort'的get变量。和' sch'在url中,但是当我打印self.kwargs时,它返回null。如果有人能指出我正确的方向,那将非常感激!

Views.py - 工具列表

class ToolList(SearchableListMixin, SortableListMixin, ListView):
    model = ToolCalibration
    template_name = 'tool_cal/list.html'
    paginate_by = 10
    context_object_name = 'tools'
    search_fields = ['description', 'notes', 'tolerance_notes']
    sort_fields_aliases = [
        ('description', 'by_description'), 
        ('last_certified', 'by_last_certified'), 
        ('due_date', 'by_due_date'), 
        ('tool_status', 'by_tool_status'), 
        ]

    def get_queryset(self, **kwargs):
        qs = super(ToolList, self).get_queryset()
        print(self.kwargs)
        sort = 'due_date'
        ### PROBLEM IS HERE. FOR SOME REASON KWARGS ISN'T GRABBING GET VARIABLES ###
        if 'sort' in self.kwargs:
            sort = self.kwargs['sort']
        try:
            schema = self.kwargs['sch']
            print 'Context using %s' % schema
            return qs.filter(schema__abbrev=schema).order_by(sort)
        except:
            print 'Context contains no schema'
            return qs.order_by(sort)

    def get_context_data(self, **kwargs):
        context = super(ToolList, self).get_context_data(**kwargs)
        context['enterprise'] = EnterpriseSchema.objects.all()
        return context

2 个答案:

答案 0 :(得分:6)

可以使用GET对象访问

request个参数。 request对象具有属性GETQueryDict实例,它是类似字典的对象。同样,也可以使用POST对象访问request个参数。在Django 1.7之前,您可以使用属性GET访问POSTREQUEST个参数。这已被弃用,因为最好使用更明确的GETPOST属性。

# GET parameters
self.request.GET.get('sort')
self.request.GET.get('sch')

# POST parameters
self.request.POST.get('key')

# Prior to Django 1.7, you can do
self.request.REQUEST.get('key') # this is either a GET or POST parameter

答案 1 :(得分:0)

尝试在urls.py中捕获变量。像

这样的东西
urlpatterns = patterns('',
url(r'^(?P<sort>\w+)/(?P<sch>\w+)/', yourview),