超长字符串的分页 Django 1.11 (Python 3.6)

Pagination for very long string Django 1.11 (Python 3.6)

我正在尝试创建自己的博客网站,其中可能包含一个很长的故事(来自数据库中的一个字段)。我在我的其他视图上成功地为记录列表(对于故事列表)创建了分页,并尝试从 Django 文档中进行试验。我所做的是从非常长的字符串创建一个数组,以便 django 分页可以计算它。

"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)

我成功创建了它,但是它是一个从上到下的单词列表,而不是看起来一点也不好的段落格式。

"post_detail.html"

{% for word_con in word_content %}
            <p class="text-justify">{{ word_con }}</p>
{% endfor %}

我试着用这个来连接它:

{% for word_con in word_content %}
            <p class="text-justify">{{ ' '.join(word_con) }}</p>
{% endfor %}

但出现错误。

我认为你的做法不对。您可以使用 Ajax 来加载更多内容,而不是对内容使用分页,加载更多按钮将加载您的 post 的内容。

内容流将是这样的,首先加载 500 个字符,然后在用户按下加载更多按钮后,然后执行 ajax 调用并带来下一个 500 个字符并附加到先前的内容。等等。

我终于找到了解决此问题的方法。这不是最佳分辨率,但对我有用。

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)

我没有计算所有字符,而是决定按段落拆分字符串并将其保存在一个数组中,这就是我在模板文件中分页的数组

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