我有以下代码。我试图传递一个名为' sort'的get变量。和' sch'在url中,但是当我打印self.kwargs时,它返回null。如果有人能指出我正确的方向,那将非常感激!
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
答案 0 :(得分:6)
GET
对象访问 request
个参数。 request
对象具有属性GET
,QueryDict
实例,它是类似字典的对象。同样,也可以使用POST
对象访问request
个参数。在Django 1.7之前,您可以使用属性GET
访问POST
或REQUEST
个参数。这已被弃用,因为最好使用更明确的GET
或POST
属性。
# 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),
)