I'm trying to create my own blog site which might contain a very long story (from one field in database). I successfully create pagination for list of records (for the list of stories) on my other views and tried to experiment from the Django documentation. What I did is create an array from the very long string so django pagination can count it.
"views.py"
def post_detail(request, slug=None): #retrieve
instance = get_object_or_404(Post, slug=slug)
words_list = instance.content.split()
paginator = Paginator(words_list, 500) # Show 25 contacts per page
page = request.GET.get('page')
try:
words = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
words = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
words = paginator.page(paginator.num_pages)
if instance.draft or instance.publish > timezone.now().date():
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
share_string = urlquote_plus(instance.content)
context = {
"title": instance.title,
"instance": instance,
"share_string": share_string,
"word_content": words,
}
return render(request, "post_detail.html", context)
I successfully created it but as a list of words from top to bottom instead of paragraph format which doesn't look good at all.
"post_detail.html"
{% for word_con in word_content %}
<p class="text-justify">{{ word_con }}</p>
{% endfor %}
I tried to concatinate it using this:
{% for word_con in word_content %}
<p class="text-justify">{{ ' '.join(word_con) }}</p>
{% endfor %}
but gets an error.
I finally found a workaround to make this work. This is not the best resolution but it works for me.
def post_detail(request, slug=None): #retrieve
instance = get_object_or_404(Post, slug=slug)
#Detect the breaklines from DB and split the paragraphs using it
tempInstance = instance.content
PaginatedInstance = tempInstance.split("\r\n\r\n")
paginator = Paginator(PaginatedInstance, 5) #set how many paragraph to show per page
page = request.GET.get('page', 1)
try:
Paginated = paginator.page(page)
except PageNotAnInteger:
Paginated = paginator.page(1)
except EmptyPage:
Paginated = paginator.page(paginator.num_pages)
context = {
"Paginated": Paginated, #will use this to display the story instead of instance (divided string by paragraph)
}
return render(request, "template.html", context)
Instead of counting all the characters, I decided to split the string per paragraph and saved it in an array and that is the one that I paginated on the template file
{% for paginatedText in Paginated %}
{{ paginatedText }}
{% endfor %}