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上申請嗎? –