Django URL冲突尽管有特定的观点

时间:2017-05-29 13:29:51

标签: python django

当有人在我的搜索框中进行搜索时(相当于“搜索”视图),我遇到了问题。单词' search'正在被“search_category”'查看并尝试使用单词' search'运行查询相反。我想我可以看到它为什么会发生 - 实际上搜索和search_category视图都在我的网址后面找一个单词。我很困惑为什么实际观点没有被提起并且网址混淆了?以下是我的观点:

我的网址

urlpatterns = [
    url(r'^(?P<letter>[a-zA-Z])/$', views.mineral_letter, name='letter'),
    url(r'^(?P<category>[a-zA-Z\s]+)/$', views.search_category, name='category'),
    url(r'^$', views.mineral_list, name='list'),
    url(r'^(?P<pk>\d+)/$', views.mineral_detail, name='detail'),
    url(r'^search/$', views.search, name='search'),
]

我的观点:

def mineral_list(request):
    minerals = Mineral.objects.all()
    return render(request, 'minerals/mineral_list.html', {'minerals': minerals})


def mineral_detail(request, pk):
    mineral = Mineral.objects.get(pk=pk)
    return render(request, 'minerals/mineral_detail.html', {'mineral': mineral})


def mineral_letter(request, letter):
    minerals = Mineral.objects.filter(name__istartswith=letter.lower())
    return render(request, 'minerals/mineral_list.html', {'minerals': minerals, 'active_letter':letter})


def search(request):
    term = request.GET.get("q")
    minerals = Mineral.objects.filter(name__icontains=term)
    return render(request, 'minerals/mineral_list.html', {'minerals': minerals})


def search_category(request,category):
    minerals = Mineral.objects.filter(category__icontains=category)
    return render(request,'minerals/mineral_list.html', {'minerals':minerals})

1 个答案:

答案 0 :(得分:2)

尝试此订单:

urlpatterns = [
    url(r'^$', views.mineral_list, name='list'),
    url(r'^search/$', views.search, name='search'),
    url(r'^(?P<letter>[a-zA-Z])/$', views.mineral_letter, name='letter'),
    url(r'^(?P<category>[a-zA-Z\s]+)/$', views.search_category, name='category'),
    url(r'^(?P<pk>\d+)/$', views.mineral_detail, name='detail'),
]