Search code examples
pythondjangopaginationmarkdowndjango-pagination

Django 1.11 Pagination Markdown


I tried to paginate a very long string in Django by splitting it using an array which I successfully did however the django-markdown-deux stopped working.

Here is how I implemented it: models.py:

class Post(models.Model):
content = models.TextField()

def get_markdown(self):
    content = self.content
    markdown_text = markdown(content)
    return mark_safe(markdown_text)

views.py:

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 = {
    "instance": instance,
    "Paginated": Paginated,  #will use this to display the story instead of instance (divided string by paragraph)
}

return render(request, "post_detail.html", context)

post_detail.html:

this is the one that works(without pagination):

{{ instance.get_markdown }}

this one works as plain text if I remove the .get_markdown and won't display anything if I put .get_markdown

{% for paginatedText in Paginated %}
{{ paginatedText.get_markdown }}
{% endfor %}

Solution

  • You paginatedText instance does not have a get_markdown method defined. Therefore, the template fails silently when you try to call it. You will need to use the markdown filter instead:

    {% load markdown_deux_tags %}
    
    {% for paginatedText in Paginated %}
    {{ paginatedText|markdown }}
    {% endfor %}