I am creating my custom admin panel in Django, i don't want to use django default admin panel, But i want sorting filters in dajngo, If a user click on email
then email should be in ascending
order, and if the user click again on email then the emails
will be in descending order, Please let me know how i can do it.
Here is my models.py
file...
class Model1(models.Model):
email= models.Charfield(blank=True)
phone= models.Charfield(blank=True)
here is my views.py
file...
def display_data(request):
test_display=UserFilter(request.GET,
queryset=Model1.objects.select_related('customer__user))
paginator = Paginator(test_display.qs, 10)
page_number = request.GET.get('page')
testdisplay = paginator.get_page(page_number)
return render(request, 'page.html', {'test_display':test_display, 'testdisplay':testdisplay})
here is my page.html
file
<th><a href="javascript:void()">Email (CLick on this field)</a></th>
{% for i in testdisplay %}
<tr>
<td>
{{i.email}}
</td>
</tr>
{% endfor %}
here is my filters.py
file code...
calss UserFilter(django_filters.FilterSet):
class Meta:
models= Model1
fields ['type','status']
You can try like this:
# template
<th><a href="?order_by=email">Email (CLick on this field)</a></th>
# view
def display_data(request, id):
test_display=Model1.objects.all()
order_by = request.GET.get('order_by', None)
if order_by:
test_display = test_display.order_by(order_by)
return render(request, 'page.html', {'test_display':test_display})
Here I am sending a URL querystring parameter order_by
. In the view, it will get the querystring parameter from request.GET
, and then order that queryset accordingly.
Based on documentation you can add OrderingFilter
:
from django_filters import FilterSet, OrderingFilter
class UserFilter(FilterSet):
order_by = OrderingFilter(fields=(('email','email')))
# rest of the code
And update the link in HTML:
<a onClick="window.location.href=window.location.pathname+'?order_by=email&'+window.location.search.substring(1)">
I am using inline JavaScript to resolve this issue, you can write a proper function for this.