0

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

“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 %} 

我试着用这concatinate它:

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

,但得到一个错误。

+0

我要让分页的一个像这样:https://pagely.com/blog/2015/03/wordpress-auto-post-pagination/ –

回答

0

我终于找到了解决方法,使这项工作。这不是最好的解决方案,但它适用于我。

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 %} 
0

尝试:

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

详情templates join

+0

我试过但仍然一样,我会尝试检查你给的文档。 –

+0

请显示您的错误代码,将其添加到问题 –

+0

实际上没有出现错误消息。它只是稍微改变了列表的外观,但仍然和以前一样。 –

1

我觉得你是不是在正确的方式做。您可以使用Ajax来加载更多内容,而不是使用分页内容,加载更多按钮将加载您的文章内容。

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

+0

我会试试看。但是建议这样做,而不是做分页,因为如果内容在文档文件中完成,内容可能会达到50页。 –

+0

正如你在你的问题中提到的那样,你需要为你的博客分配内容吗?然后根据我,你应该通过加载你的内容逐渐500字符500字符做到这一点。如果您认为您的内容大小超过50页,则可以在一次或多次加载更多的ajax请求后增加角色(最多1500个字符)。如果你想知道如何做到这一点,请告诉我。谢谢。 –

+0

是的。你能举个例子说我可以在django上申请吗? –