1

The URL pattern having issues is:

url(r'^$', business_list, name='business_list_home'),
url(r'^(?P<param>\w+)$', business_list, name='business_list_results'),

My view is:

@render_to('app/business_list.html')
def business_list(request, param=None):
    queryset = Business.objects.all()

    search_form = SearchForm
    print request.GET

    if param in request.GET:
        param = request.GET.get('param')
        if queryset.filter(city__iexact=param).exists():
            queryset = queryset.filter(city__iexact=param)
        elif queryset.filter(category__iexact=param).exists():
            queryset = queryset.filter(category__iexact=param)
        print queryset
    else:
        queryset = None
        print queryset

return {'business_list': queryset, 'search_form': search_form}

Essentially, I don't understand why when I go to /Miami I don't have access to it via request.GET['param'] in the view? print request.GET prints <QueryDict: {}>

The reason I want to do this is to have a nice URL scheme for displaying results of businesses for the city or category (and that's why I check if it's a city or category in the view too) in the url. Let me know if there's a better way to accomplish this like

url(r'^$', business_list),
url(r'^(?P<city>\w+)$', business_list),
url(r'^(?P<category>\w+)$', business_list),
url(r'^(?P<category>\w+)/(?P<city>\w+)$', business_list),

Thanks for any help!

4

1 回答 1

2

business_list是一个函数,它接受一个请求和一个名为“param”的参数(应该给它一个更好的名字,让它不那么通用)。在 Django 中,URL 路由可以定义将哪些值传递给视图函数的参数。

在上述情况下,当用户访问 时/Miami,Django 将尝试将字符串"Miami"与 URL 路由中定义的任何正则表达式进行匹配。在这种情况下,匹配表达式是^(?P<param>\w+)$。进行此匹配后,该字符串Miami将被捕获到param.

然后 Django 将调用business_list(request, param="Miami"). 请注意,在 URL 中没有传递查询参数(例如,/Miami?color=blue)。

您在上面编写的代码中的问题是您正在检查的不是是否param存在,而是param查询参数中是否存在。尝试访问 URL /Miami?param=test,它可能会按照您预期的方式工作。

这里真正的解决方法是不引用request.GET,因为使用 GET 参数正是您要避免的。所以,而不是

if param in request.GET:
    param = request.GET.get('param')
    if queryset.filter(city__iexact=param).exists():
        queryset = queryset.filter(city__iexact=param)
    elif queryset.filter(category__iexact=param).exists():
        queryset = queryset.filter(category__iexact=param)
    print queryset

做就是了:

if param:
    if queryset.filter(city__iexact=param).exists():
        queryset = queryset.filter(city__iexact=param)
    elif queryset.filter(category__iexact=param).exists():
        queryset = queryset.filter(category__iexact=param)
于 2013-05-27T17:38:52.523 回答