Django错误:没有匹配的FlatPage查询
SITE_ID = 1
还有
(r'', include('django.contrib.flatpages.urls')),
这个在 urls.py
文件里。
我该怎么做才能解决这个错误?Django 还是显示这个错误 - 我在网上搜索过,但找不到任何信息。
文件 urls.py
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'cms.views.home', name='home'),
# url(r'^cms/', include('cms.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
(r'', include('django.contrib.flatpages.urls')),
)
这是最基本的 urls.py
文件。所以我没必要贴代码,但这里还是给你看一下。
这个功能也是启用的。因为这是一个新项目,我会展示每个文件。
_init_ 是空的
settings.py
# Django settings for CMS project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'C:\Documents and Settings\Administrator\Desktop\django-projects\cms/cms.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'o2lqxjp!fg%0xod5g$79alt_*o4&lkw-ncr^30iuqcv(y-44i7'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.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',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)
ROOT_URLCONF = 'cms.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.flatpages',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
最后是 manage.py
:
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)
import settings
if __name__ == "__main__":
execute_manager(settings)
在管理界面中,flatpages 功能正常
我确实通过管理界面添加了那个页面
这是我的数据库路径:
C:\Documents and Settings\Administrator\Desktop\django-projects\cms\cms.db
当我运行 python manage.py syncdb
时,没有看到任何错误。
我尝试访问
http://localhost:8000/test/
当我输入
python manage.py runserver
时,也没有看到任何错误。
管理界面工作得很好。
3 个回答
为了完整起见,我想分享一下我遇到这个错误的另一个原因。
问题出在保存平面页面的链接时,没有在前面加上斜杠。
抛出这个错误的视图会在链接前面没有斜杠的情况下更改链接。所以当我把 'example/' 存到数据库时,就出现了问题。
# This is the view function where the error occurs.
# I stored 'example/' as url to db.
def flatpage(request, url):
if not url.startswith('/'):
# Here the url is manipulated and becomes '/example/':
url = '/' + url
site_id = get_current_site(request).id
try:
# '/example/' does not exist in db:
f = get_object_or_404(FlatPage, url=url, sites=site_id)
我在使用 Django 的 flatpages 时遇到了同样的问题。这个问题和你的网站 ID 有关。
当我尝试从管理后台添加 flatpage,并为我的 flat page 添加一个网站时,发现“sites”字段里有一个 example.com,它的 SITE_ID 是 1(可以通过 django_site 表查看)。
举个例子:我在管理后台添加了一个 flat page,设置如下: url = '/about/' site = "localhost:8000" name = "about" content = "这是关于页面"
*如果你是在本地开发,可能需要把 localhost:8000 添加到你的网站中。这样新添加的网站(localhost:8000)就会有 SITE_ID=2。*
你可以通过查看你在设置文件中提到的数据库里的 django_site 表来确认这一点。
现在,找到 localhost:8000 的 SITE_ID(这是 django_site 表中的主键),然后在设置文件中把你的 SITE_ID 修改为这个 SITE_ID(也就是 localhost:8000 的 SITE_ID)。
就这样,打开浏览器访问 "localhost:8000/about/"(假设你已经在你的应用中扩展了 flatpage,具体可以参考 https://docs.djangoproject.com/en/dev/ref/contrib/flatpages/)。
我觉得这个错误是,你不需要为 flatpages
创建一个 urls.py
文件。相反,你需要做的是:
在你的 MIDDLEWARE_CLASSES 设置中添加 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware'。
这段话是引用自 Django 的文档,平面页面应用。
检查代码和项目后发现,问题在于在 admin
界面编辑或创建平面页面时,你必须选择一个或多个网站来关联。