I have problems with sorting objects from database in main template which are based on url parameters. I want to sort objects on different ways. Mainly by date, price etc. I have my form in template, my views.py function where I'm trying to get the parameter "sort=new". If I'm using checkboxes or radio then everything works. But I need to sort objects with select and option. My template:
<h2>Number of adverts: {{num}}</h2>
<form action="{% url 'adverts' %}">
<span>Sort by:</span>
<select name="sort">
<option value="new">newest</option>
<option value="old">older</option>
<option value="price_low">price low</option>
<option value="price_high">price high</option>
<option value="mileage_low">mileage lowest</option>
<option value="mileage_high">mileage higher</option>
<input type="submit" value="Sort">
</select>
</form>
My views.py function:
def adverts(request):
page = 'adverts'
if request.GET.get('sort', 'new'):
adverts = Advert.objects.all().order_by('-created')
elif request.GET.get('sort','old'):
adverts = Advert.objects.all().order_by('created')
else:
adverts = Advert.objects.all().order_by('-mileage')
a = 0
for num in adverts:
a = 1
context = {'adverts': adverts, 'num': a, 'page': page}
return render(request, 'adverts/adverts.html', context)
As I mention above. I want to sort objects which I’m printing in my template. I want it to be a Dropdown list not a checkbox or radio. Maybe I need to create a form in forms.py file and then get access to form fields in my template? I’m confused.
CodePudding user response:
You should check the value of the sort
parameter, so:
def adverts(request):
page = 'adverts'
adverts = Advert.objects.all()
sort_by = request.GET.get('sort') #