【问题标题】:Django Pagination not giving resultsDjango Pagination 没有给出结果
【发布时间】:2013-07-13 23:36:25
【问题描述】:

我正在制作一个 Django 项目,一个企业目录。这里我在 html 页面中使用了 Pagination。但它不起作用,。 它也没有显示任何错误 请检查我的代码并帮助我解决我的问题

我的models.py是::

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

我的 view.py 是 ::

   # 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})

以及我在html页面中使用的代码:

<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>

而settings.py文件是::

# 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,
        },
    }
}

请帮忙解决分页问题。 请,,....

【问题讨论】:

    标签: python django python-2.7 django-templates django-views


    【解决方案1】:

    我 90% 确定这是由您的 listing 视图中的以下 2 行引起的:

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

    search 不是已定义的变量。也许您可能一直在尝试调用search(),但即使这样也会返回一个您无法分页的HttpResponse。

    您传递给Paginator() 的第一个值应该是多个对象/项目的集合。例如,Paginator(Photos.objects.all(), 10) 每页显示 10 张照片。


    顺便说一句,您的观点与您的符号有点不一致。例如,

    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))
    

    可以改写为

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

    这与您在 search 视图中所做的类似。


    另一方面,出于明显的安全原因,您不应公开显示您的 SECRET_KEY 值。只是想帮忙!

    【讨论】:

      【解决方案2】:

      您有什么理由不使用基于类的视图?您可以修改一个分页属性,它会自动给您分页!

      from django.views.generic import ListView
      
      class BusinessView(ListView):
          model = YourBusinessModel
          paginate_by = 20
      

      这里还有一些文档:

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

      祝你好运!

      【讨论】:

        猜你喜欢
        • 2018-11-30
        • 2014-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-17
        • 2018-11-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多