As in title. I have a problem becasue I am not able to sort items which I browsed. Or should I use Javascript than pure Django to perform things like these?
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>
CodePudding user response:
In your HTML code try to use 'name' instead 'value' it could help. For example:
<option name="v1">Price: low to high</option>
source: Django:get field values using views.py from html form
Regarding to your function name searchView(request). In Python we are using snake_case for function naming (https://en.wikipedia.org/wiki/Snake_case). CamelCase is reserved for class naming.
regards
CodePudding user response:
Finally I have done it, the problem was 2 diffrent forms.
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')
I would be pleased if someone can tell me is using search_history = []