我开始学习Django,我遇到了一个问题:我不能在链接中添加参数
示例:
更改之前的链接:
http://127.0.0.1:8000/?brand=&search=更改后的链接:
http://127.0.0.1:8000/?brand=&search=&sort=我得到的是:
http://127.0.0.1:8000/?sort=如何实施?
views.py
def filters(request):
#search
search_post = request.GET.get('search', '')
if search_post:
all = Product.objects.filter(Q(title__icontains=search_post) & Q(content__icontains=search_post)).order_by()
else:
all = Product.objects.all()
#sort by price
sort_by = request.GET.get("sort", '')
if sort_by == "l2h":
all = Product.objects.all()
all = all.extra(order_by = ['-price'])
elif sort_by == "h2l":
all = Product.objects.all().order_by('price')
filters = IndexFilter(request.GET, queryset=all)
context = {
'filters': filters
}
return render(request, 'index.html', context)urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('', filters, name='filters')
]index.html
<form method="get" action="{% url 'filters' %}">
{{ filters.form }}
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
<a class="filter_by" href="?sort=l2h">Price:--low to high</a>
<a class="filter_by" href="?sort=h2l">Price:-- high to low</a>
</form>发布于 2022-10-02 08:01:03
您已经在代码中定义了2个锚点标记,它完全改变了URL,不会向URL添加新的查询参数。
<a class="filter_by" href="?sort=l2h">Price:--low to high</a>
<a class="filter_by" href="?sort=h2l">Price:-- high to low</a>您需要做的是编写一些javascript代码,并使用URLSearchParams将这种排序添加到现有的url参数中。
使用this answer将参数追加到url。
或者没有javascript,您可以将这些参数发送到模板并更改href。
def filters(request):
#search
search_post = request.GET.get('search', '')
if search_post:
all = Product.objects.filter(Q(title__icontains=search_post) & Q(content__icontains=search_post)).order_by()
else:
all = Product.objects.all()
#sort by price
sort_by = request.GET.get("sort", '')
if sort_by == "l2h":
all = Product.objects.all()
all = all.extra(order_by = ['-price'])
elif sort_by == "h2l":
all = Product.objects.all().order_by('price')
filters = IndexFilter(request.GET, queryset=all)
context = {
'filters': filters,
'search': search_post,
'brand': request.GET.get('brand', '')
}
return render(request, 'index.html', context)<form method="get" action="{% url 'filters' %}">
{{ filters.form }}
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
<a class="filter_by" href="?search={{ search }}&brand={{ brand }}&sort=l2h">Price:--low to high</a>
<a class="filter_by" href="?search={{ search }}&brand={{ brand }}&sort=h2l">Price:-- high to low</a>
</form>https://stackoverflow.com/questions/73923922
复制相似问题