Как выполнить сортировку просмотренных элементов в Django
Как в заголовке. У меня проблема, потому что я не могу сортировать элементы, которые я просматривал. Или я должен использовать Javascript, а не чистый Django для выполнения таких вещей?
views.py
def searchView(request):
if request.method == "GET":
context = request.GET.get('search')
if not context:
context = ""
items = Item.objects.all().filter(title__icontains=context)
try:
sorting_method = request.GET.get('select')
if sorting_method == 'v1':
items = items.order_by('price')
elif sorting_method == 'v2':
items = items.order_by('-price')
else:
return render(request, 'shop/search.html', {'items': items})
return render(request, 'shop/sort.html', {'items': items})
except UnboundLocalError:
return redirect('home-page')
HTML :
<form action="{% url 'search-page'%}" class="navbar__search-form" method="GET">
<input name="search" class="navbar__search-text" type="text" placeholder="Search for an item.">
</form>
<form action="{% url 'search-page'%}" class = "sort__form" method="GET">
<h1 class="sort__header"> SORT ITEMS </h1>
<select class= "sort__select" name="select">
<option disabled selected> Sorting method</option>
<option value="v1">Price: low to high</option>
<option value="v2">Price: high to low</option>
</select>
<button class="sort__submit">SORT</button>
</form>
В вашем HTML-коде попробуйте использовать 'name' вместо 'value', это может помочь. Например:
<option name="v1">Price: low to high</option>
источник: Django:получить значения полей с помощью views.py из html-формы
Что касается названия вашей функции searchView(request). В Python мы используем змеиный регистр для именования функций (https://en.wikipedia.org/wiki/Snake_case). CamelCase зарезервирован для именования классов.
regards
Наконец-то я сделал это, проблема была в двух разных формах.
views.py
search_history = []
def searchView(request):
if request.method == "GET":
context = request.GET.get('search')
if not context:
context = search_history[-1]
search_history.append(context)
items = Item.objects.all().filter(title__icontains=search_history[-1])
try:
sorting_method = request.GET.get('select')
if sorting_method == 'v1':
items = items.order_by('price')
return render(request, 'shop/search.html', {'items': items})
if sorting_method == 'v2':
items = items.order_by('-price')
return render(request, 'shop/search.html', {'items': items})
else:
return render(request, 'shop/search.html', {'items': items})
except UnboundLocalError:
return redirect('home-page')
Буду рад, если кто-нибудь подскажет мне, используется ли search_history = []