N
N
Nem0_o2014-07-12 21:53:40
Django
Nem0_o, 2014-07-12 21:53:40

How to use paginator?

Hello! I must say right away that I am new to Python & Django. I can't deal with pagination, I tried to do it according to the documentation - http://djbook.ru/rel1.6/topics/pagination.html , but it didn't work, can anyone explain, show?
There is view.py:

from blog.models import Post from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django.views.generic import ListView, DetailView

class PostsListView(ListView):

queryset = Post.objects.all().order_by('-datetime')

class PostDetailView(DetailView):

model = Post

There is models.py:
from django.db import models

class Post(models.Model): title = models.CharField(max_length=255)

datetime = models.DateTimeField(u'Дата публикации')

content = models.TextField(max_length=10000)

def unicode(self):

return self.title

def get_absolute_url(self):

return "/blog/%i/" % self.id

And also 3 templates, base.html :
{% load staticfiles %} 
<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8">
        <title>Блог на Django</title>
     <link rel="stylesheet" type="text/css" href="{% static 'bootstrap/css/bootstrap.css' %}" />
    
       <style>
            body {
                padding:93px 10px; 
        background:#ECF0F1;
        
      }
      .list{
        width:150px;
        color:#EA6153;
      }
      .header{
        color:#EA6153;
        text-align:center;
        font-size:25px;
        font-weight:bold;
      }
  
        </style>
    
        <!--[if lt IE 9]>
        <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
    
    </head>
<body>

<div class="navbar navbar-inverse navbar-fixed-top" class="upper">
    <div class="navbar-inner">
        <div class="">
            <div class="header">Блог на Django</div>
            <ul class="nav">
                <li><a href="{% url 'list' %}" class="list">Список постов</a></li>
            </ul>
        </div>
    </div>

</div>
     {% block content %}Empty page{% endblock %}
</div> <!-- container -->

</body>
</html>

post_list.html :
{% extends 'blog/base.html' %}
{% block content %}
    {% for post in object_list %}
  <style>
    #content{
        width:550px;
        height:155px;
        overflow:hidden;
        margin:10px auto;
        padding-left:5px;
        border-top:5px solid #EA6153;
    }
    #datetime{
      color:#34495E;
      font-weight:bold;
      text-decoration:underline;
    }
    
    
  </style>
  <div id="content">
        
        <h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2>
    <p id="datetime">{{ post.datetime }}</p>
        <p>{{ post.content }}</p>
  </div>
    {% empty %}
    <p>Нет постов</p>
    {% endfor %}

{% endblock %}

post_detail.html :
{% extends 'blog/base.html' %}
{% block content %}
  <style>
    h2{
      color:#428BCA;
    }
    #datetime{
      color:#34495E;
      font-weight:bold;
    }
    
  </style>
    <p id="datetime">{{ post.datetime }}</p>
    <h2>{{ post.title }}</h2>
    <p>{{ post.content }}</p>
{% endblock %}

What should be written in them?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sim3x, 2014-07-13
@Nem0_o

We do everything based on what you do everything through CBV. That manual that you pass concerns simple view-functions.
It is worth trying to write both CBV and functional views.
0. Install django-debug-toolbar
1. Poke around in all debug toolbar tabs. This is an important part of the development
2. Fumble around the variables that you have passed to the template. You will be interested in such variables as object_list, post_list. These are synonyms for the list that the queryset gave you.
The second name (post_list) is a variable from the model from the Meta subclass
verbose_name_plural + '_' + 'list'

class PostsListView(ListView):
    queryset = Post.objects.all().order_by('-datetime')
    # context_object_name это та переменная о которой я говорил выше
    # можно задать свое имя
    # context_object_name = "car_list"    
    paginate_by = 10  # количество постов на страницу

doplink
stackoverflow.com/a/5910325/1346222
model note
class Post(models.Model): 
    title = models.CharField(max_length=255)
    datetime = models.DateTimeField(u'Дата публикации')
    content = models.TextField(max_length=10000)

# было
# def unicode(self):
#    return self.title

# Надо
def __unicode__(self):
    return self.title


# было
# def get_absolute_url(self):
#   return "/blog/%i/" % self.id

# а стоит использовать всю магию джанго
# в urls.py есть вот такое
# url(r'^/blog/(?P<pk>\d+)/$', PostDetailView.as_view(), name='blog_post'), 
# и можно сделать так, чтобы любое изменение urls.py было подхвачено 
# в модели автоматом
# те модель сама узнает как стоит делать ссылку на блогпост
    @models.permalink
    def get_absolute_url(self):
        return 'blog_post', (), {'pk': self.pk}

upd:
{% if is_paginated %}
<ul class="pagination">
  {% if post_list.number != post_list.previous_page_number %}
    <li><a href="?page={{ post_list.previous_page_number }}">&larr;</a></li>
  {% endif %}

  {% for page in post_list.paginator.page_range %}
    {% if page != post_list.number %}
      <li><a href="?page={{ page }}">{{ page }}</a></li>
    {% else %}
      <li class="active">{{ page }}</li>
    {% endif %}

  {% endfor %}
  {% if post_list.number != post_list.next_page_number %}
    <li><a href="?page={{ post_list.next_page_number }}">&rarr;</a></li>
  {% endif %}
</ul>
{% endif %}

Here is such a construction
?page={{ post_list.previous_page_number }}
simply adds ?page= to the current url
By url I mean site.com/blog/

Y
yttrium, 2014-07-12
@yttrium

Everything is written here . We get the page number from GET or a piece of the url.. We create a paginator in the view based on the selection.. We register it in the template

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question