Last active
March 18, 2021 16:54
-
-
Save m3ldis/a3535e64a9b314339a2e1aabdfb4d1c7 to your computer and use it in GitHub Desktop.
Django next/previous item
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
:root { | |
--grey-100: #fafafa; /* 98 */ | |
--grey-200: #e6e6e6; /* 90 */ | |
--grey-300: #d4d4d4; /* 83 */ | |
--grey-400: #bfbfbf; /* 75 */ | |
--grey-500: #a6a6a6; /* 65 */ | |
--grey-600: #8c8c8c; /* 55 */ | |
--grey-700: #737373; /* 45 */ | |
--grey-800: #555; /* 33 */ | |
--grey-900: #333; /* 20 */ | |
--grey-blue-300: #cbd5db; /* 83 */ | |
--grey-blue-900: #253241; /* 20 */ | |
} | |
a:not(:disabled) .nav-btn { | |
color: var(--grey-900); | |
} | |
button:disabled .nav-btn { | |
color: var(--grey-500); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# save under templatetags/ | |
from django import template | |
register = template.Library() | |
@register.filter(name="next_item") | |
def get_next(obj): | |
X = obj.__class__ | |
qs =X.objects.filter(id__gt=obj.pk) | |
return qs[0].id if qs else 0 | |
@register.filter(name="previous_item") | |
def get_previous(obj): | |
X = obj.__class__ | |
qs = X.objects.filter(id__lt=obj.pk).order_by('-pk') | |
return qs[0].id if qs else 0 | |
""" | |
# for custom order_by, this would probably work: | |
def get_previous(obj, order_by): | |
X = obj.__class__ | |
qs = X.objects.filter(**{f'{order_by}__lt': getattr(obj, order_by)}).order_by(f'-{order_by}') | |
return qs[0].id if qs else 0 | |
# in template: | |
{{ object|next_item:"sort_attribute" }} | |
""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% if object|previous_item %} | |
<a class="ml-4 btn btn-light" href="{% url 'myobj-detail' object|previous_item %}"><i class="fa fa-arrow-left nav-btn"></i></a> | |
{% else %} | |
<button class="ml-4 btn btn-light" href="#" disabled><i class="fa fa-arrow-left nav-btn"></i></button> | |
{% endif %} | |
{% if object|next_item %} | |
<a class="ml-4 btn btn-light" href="{% url 'myobj-detail' object|next_item %}"><i class="fa fa-arrow-right nav-btn"></i></a> | |
{% else %} | |
<button class="ml-4 btn btn-light" disabled><i class="fa fa-arrow-right nav-btn"></i></button> | |
{% endif %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment