我试图创建自己的博客网站,其中可能包含很长的故事(来自数据库中的一个字段)。我在其他视图上成功创建了记录列表(故事列表)的分页,并尝试从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 %}
但是收到错误。
答案 0 :(得分: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 %}