I'm working on a django project trying to create a forum. Now when a certain number of objects (thread-previews) is reached on one page, I want a second (and then third page etc) page created and some of these objects should go to these next pages (page 2, then page 3 etc.) and the url for the second page should be something like "mysite.com/fourum/topic/2" and so on.
And then there have to be some buttons to navigate to page 2, page 3 etc.
This would be relevant code:
gaming.html
{% extends "forum/index.html" %}
{% load static %}
{% block title %} Gaming {% endblock %}
{% block content %}
<div >
<h1 >Forum: Gaming</h1>
{% for obj in object %}
<div >{{obj.username}}</div>
<div >{{obj.date}}</div>
<div >{{obj.topic}}</div>
<div ><a href="{{obj.slug_titel}}">{{obj.title}}</a></div>
<div >{{obj.content}}</div>
{% endfor %}
</div>
{% endblock %}
views.py
def gaming(request):
obj = Threads.objects.filter(topic="gaming")
context = {
"object": obj,
}
return render(request, "forum/gaming.html", context)
CodePudding user response:
I think what you describe looks like django pagination.
Within your view, something as follow could do the trick :
...
from django.core.paginator import Paginator
...
def gaming(request):
threads = Threads.objects.filter(topic="gaming")
paginator = Paginator(threads, 25) # Show 25 contacts per page.
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, "forum/gaming.html", {'page_obj': page_obj, **context})
On the template add following :
<div >
<span >
{% if page_obj.has_previous %}
<a href="?page=1">« first</a>
<a href="?page={{ page_obj.previous_page_number }}">previous</a>
{% endif %}
<span >
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">next</a>
<a href="?page={{ page_obj.paginator.num_pages }}">last »</a>
{% endif %}
</span>
</div>
Beside i recommend you to read the documentation about the subject : https://docs.djangoproject.com/fr/4.0/topics/pagination/