简体   繁体   中英

Django Pagination not giving results

I am making a Django Project, A Business Directory. Here I have used the Pagination in the html page. But its not working,. and its not showing any error also please check my codes and help me to solve my problem

my models.py is::

from django.db import models


class Directory(models.Model):

    Bussiness_name = models.CharField(max_length=300)
    Description = models.CharField(max_length=900)
    Number = models.CharField(max_length=100)
    Web_url = models.CharField(max_length=800)
    Catogory = models.CharField(max_length=200)


    def __unicode__(self):
        return self.Bussiness_name

class Adress(models.Model):
   directory =  models.ForeignKey(Directory)
   adress_name =  models.CharField(max_length=300)
   def __unicode__(self):
        return self.adress_name

class Photos(models.Model):
   directory =  models.ForeignKey(Directory)
   Photo_path =  models.CharField(max_length=100)
   Photo_name =  models.CharField(max_length=100)
   def __unicode__(self):
        return self.Photo_name

My view.py is ::

   # The views.py file
from django.http import HttpResponse
from crawlerapp.models import Directory
from crawlerapp.models import Adress
from crawlerapp.models import Photos
from django.template import Context, loader
from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

# it returns the resonse to the 1st page or Home page. 
def index(request):
    Directory_list = Directory.objects.all()
    t=loader.get_template('crawlerapp/index.html')
    c = Context({'Directory_list': Directory_list,})
    return HttpResponse(t.render(c))

 # it returns the resonse to the Contact Us page   
def contactus(request):
    Directory_list = Directory.objects.all()
    t=loader.get_template('crawlerapp/contactus.html')
    c = Context({'Directory_list': Directory_list,})
    return HttpResponse(t.render(c))

# when a catagory is searched, it takes the request and
# varifies whether it's a category or a place for which we are searching for.
def search(request):
    if 'what' in request.GET and request.GET['what']:
        what = request.GET['what']

        crawlerapp = Directory.objects.filter(Catogory__icontains=what)
        return render(request, 'crawlerapp/search.html',
                      {'crawlerapp': crawlerapp, 'query': what})


    elif 'who' in request.GET and request.GET['who']:
        who = request.GET['who']
        crawlerapp = Directory.objects.filter(Bussiness_name__icontains=who)
        return render(request, 'crawlerapp/search.html',
                      {'crawlerapp': crawlerapp, 'query': who})
  # if the form field is left blank and searched, it will give the folowing message.      
    else:
        message = 'You submitted an empty form.'  
    return HttpResponse(message)

# I tried to include paging here and has set a limit of 10
# That is per page will contain only 10 Business details and not more than 10.
def listing(request):
    directory_list = search
    paginator = Paginator(directory_list, 10) # Show 10 business details per page

    page = request.GET.get('page')
    try:
        directory = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        directory = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)

    return render_to_response('search.html', {"directory": directory})

And the code I used in html page:

<html>
<head>
      <title>{% block head_title %}SearchPage{% endblock %}</title>
</head>
<body>
    <h1>{% block title %}The Blue Day, A Search Directory by Abhimanyu Choithramani{% endblock %}</h1>
    {% block content %}
  <div style="text-transform: uppercase;" id="network-bar">
    <dl>
                     <dd>*          <a href="http://127.0.0.1:8000/crawlerapp/">Homepage</a>    

                *          <a href="http://127.0.0.1:8000/crawlerapp/contactus">Contact Us</a></dd>                 
    </dl>
    <dl>
        <dd class="last" style="float: right;"><a href="http://127.0.0.1:8000/crawlerapp/" title="Blue Day Business Directory">Blue Day Business Directory</a></dd>
    </dl>
    <div class="network-bar-search"></div>
  </div>

  <div style="border-top: 1px dashed #6b88a5; margin: 10px;"></div>

  <div style="padding: 0 10px 10px; position: relative;">
        Search our <a href="http://127.0.0.1:8000/crawlerapp/">Business Directory</a> by entering a business type or name and just click on a Search.

  </div>
        <div style="position: relative;" id="headerSearchindex">
    <form action='' method="GET">
        <table style="width: 60%" border="0" cellpadding="1" cellspacing="0">

            <tr>
                  <td class="hsTableTitleCell leftSpaced">  By category:</td>
                <td class="hsTableTitleCell leftSpaced">Or by company name:</td>
                    <td style="width: 300px;">&nbsp;</td>
            </tr>
            <tr>
                <td class="hsTableBusinessCell leftSpaced"><input  type="text" title="Business Category" placeholder="e.g Computer, Restaurants" name="what"  autocomplete="off" value=""/></td>
                <td class="hsTableCompanyCell leftSpaced"><input  type="text" title="Company Name" placeholder="e.g Smith and Sons" name="who" value=""/></td>                  

<td class="hsTableSearchButtCell leftSpaced"><input name="search_action" type="submit" value="Search"/></td>
            </tr>

        </table>
    </form>

  </div>


<p>You searched for: <strong>{{ query }}</strong></p>

{% if crawlerapp %}

<p>Found {{ crawlerapp|length }} in this Category{{ crawlerapp|pluralize }}.</p>
<ul>

{% for Directory in crawlerapp %}
<li>Business Name:  {{ Directory.Bussiness_name }}</li>
    Description:    {{ Directory.Description }}</br>
    Contact Number: {{ Directory.Number }}</br>
    Web_URL:        {{ Directory.Web_url }}</br>
    Adress:        {% for Adress in Directory.adress_set.all %}{{forloop.counter}}:-  {{ Adress.adress_name }}</br>{% endfor %}
    Photo:          {% for Photos in Directory.photos_set.all %}{{ Photos.Photo_name }}</br>{% endfor %}</br></br>

{% endfor %}

</ul>

<div class="pagination">
<span class="step-links">
    {% if Directory.has_previous %}
        <a href="?page={{ Directory.previous_page_number }}">previous</a>
    {% endif %}

    <span class="current">
        Page {{ Directory.number }} of {{ Directory.paginator.num_pages }}.
    </span>

    {% if Directory.has_next %}
        <a href="?page={{ Directory.next_page_number }}">next</a>
    {% endif %}
    </span>
</div>

{% else %}
<p>No Business matched your search criteria.</p>
{% endif %}

  </body>                       

<br><br><br><br><br><br><br><br>            

        <div id="footer"> &copy; Abhimanyu Choithramani's <a href="http://127.0.0.1:8000/crawlerapp/" >The Blue Day</a> is a Business Search Directory.
        </div>
    </div>
</div>


 {% endblock %}     


</html>

And the settings.py file is::

# Django settings for crawler project.
import os.path
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'project2',                      # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': 'root',
        'PASSWORD': '',
        'HOST': '127.0.0.1',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '3306',                      # Set to empty string for default.
    }
}

ALLOWED_HOSTS = []

TIME_ZONE = 'America/Chicago'

LANGUAGE_CODE = 'en-us'

SITE_ID = 1

USE_I18N = True

USE_L10N = True

USE_TZ = True

MEDIA_ROOT = ''

MEDIA_URL = ''

STATIC_ROOT = ''

STATIC_URL = '/static/'

STATICFILES_DIRS = (

)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',

)

SECRET_KEY = ''

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'crawler.urls'

WSGI_APPLICATION = 'crawler.wsgi.application'

TEMPLATE_DIRS = (
    os.path.join(PROJECT_ROOT, "templates/crawlertemplates")
    #  "C:/Python27/django/crawler/templates",

)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'crawlerapp',
    'django.contrib.admin',
)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

Please help to solve the problem of Pagination. PLEASE,,....

I'm 90% sure it's caused by the following 2 lines in your listing view:

directory_list = search
paginator = Paginator(directory_list, 10) # Show 10 business details per page

search is not a defined variable. Perhaps you may have been trying to call search() , but even that will return an HttpResponse which is not something you can paginate with.

The first value you pass to Paginator() should be a collection of multiple objects/items. For example, Paginator(Photos.objects.all(), 10) would display 10 photos per page.


On a side note, you are a little inconsistent with your notation in your views. For example,

def contactus(request):
    Directory_list = Directory.objects.all()
    t=loader.get_template('crawlerapp/contactus.html')
    c = Context({'Directory_list': Directory_list,})
    return HttpResponse(t.render(c))

can be rewritten as

def contactus(request):
    Directory_list = Directory.objects.all()
    return render(request, 'crawlerapp/contactus.html', {'Directory_list': Directory_list,})

which is similar to what you did in your search view.


On another side note, you shouldn't publicly display your SECRET_KEY value, for obvious security reasons. Just trying to help!

Is there any reason you aren't using class based views? There's a paginate property you can modify and it'll automatigically give you pagination!

from django.views.generic import ListView

class BusinessView(ListView):
    model = YourBusinessModel
    paginate_by = 20

Here's some more docs:

https://docs.djangoproject.com/en/1.3/ref/class-based-views/#django.views.generic.list.MultipleObjectMixin.paginate_by

Have a good one!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM