I'm starting to learn Django and I ran into this problem: I can't add parameters to the link
Example:
Link before the change:
http://127.0.0.1:8000/?brand=&search=
Link after the change:
http://127.0.0.1:8000/?brand=&search=&sort=
What I get:
http://127.0.0.1:8000/?sort=
How to implement it?
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 type="search" placeholder="Search" aria-label="Search" name="search">
<button type="submit">Search</button>
<a href="?sort=l2h">Price:--low to high</a>
<a href="?sort=h2l">Price:-- high to low</a>
</form>
CodePudding user response:
You have defined 2 anchor tags in your code which change the URL completely and won't append new query parameters to your URL.
<a href="?sort=l2h">Price:--low to high</a>
<a href="?sort=h2l">Price:-- high to low</a>
What you need to do is write some javascript code and use URLSearchParams to add this sort to existing url parameters.
Use this answer to append parameters to url.
Or without javascript you can send those parameters to your template and change the 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 type="search" placeholder="Search" aria-label="Search" name="search">
<button type="submit">Search</button>
<a href="?search={{ search }}&brand={{ brand }}&sort=l2h">Price:--low to high</a>
<a href="?search={{ search }}&brand={{ brand }}&sort=h2l">Price:-- high to low</a>
</form>