【问题标题】:Newbie. Django Tutorial (from django website) stuck at part 2 - admin新手。 Django 教程(来自 django 网站)停留在第 2 部分 - 管理员
【发布时间】:2012-08-10 21:47:30
【问题描述】:

我在这里阅读了很多答案,但没有一个回答我的确切问题。

我做了第一部分,民意调查。我开始了第 2 部分,管理员,但是,在 runserve 之后,当我尝试访问页面时,这是我得到的错误(我的项目名称是 john):

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Using the URLconf defined in john.urls, Django tried these URL patterns, in this order:
^admin/
The current URL, , didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. ``

我的代码 - urls.py:

from django.conf.urls 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'^$', 'newgrid.views.home', name='home'),
    # url(r'^newgrid/', include('newgrid.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)),
)

模型.py:

from django.db import models
import datetime
from django.utils import timezone

# Create your models here.
from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __unicode__(self):
        return self.question
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)


class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()
    def __unicode__(self):
        return self.choice

settings.py:

# Django settings for newgrid project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

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

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'C:/john/john/johny.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.
# In a Windows environment this must be set to 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

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = 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/'

# 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 = 'cl8%_lzxbct-^ebmpje25%r&5*0=$qmv9gw6i$^arox*kr4$_e'

# 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',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'newgrid.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'newgrid.wsgi.application'

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.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',
    'polls'
)

# 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 when DEBUG=False.
# 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,
    '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,
        },
    }
}

就是这样。哦,是的,我在 WinXP 中。

【问题讨论】:

  • 你记得重启吗?
  • 好问题。如果您指的是:“manage.py runserver”,那么是的。我做了 CTRL-C 并再次运行命令。结果相同。
  • 仔细阅读教程。在教程的第 3 部分之前,您将无法访问 /(索引页面)。见stackoverflow.com/questions/11832178/…

标签: django admin


【解决方案1】:

您导航到了错误的 URL。作为the tutorial says

现在,打开 Web 浏览器并转到本地域上的 /admin/例如http://127.0.0.1:8000/admin/。您应该会看到管理员的登录屏幕:

【讨论】:

    【解决方案2】:

    在您的 URLconf 中,您没有为根 URL 定义视图,这就是为什么您的应用程序只有在您将浏览器指向以 admin/ 开头的 URL 时才能工作的原因

    取消注释以下行:

    # url(r'^$', 'newgrid.views.home', name='home'),
    

    并将'newgrid.views.home' 更改为现有视图,可能会呈现包含一些临时链接的纯模板。

    【讨论】:

    • 感谢 supervacuo 和 dschulz。你们俩都是对的。这是我的错,教程明确指出指向/admin。我不知何故错过了那部分。我的错。也感谢您提供解决方案的代码。
    【解决方案3】:

    我知道很久以前有人问过这个问题,但也许人们仍然在这里寻找相同问题的答案,就像我一样。对我来说,我遇到的问题是 which urls.py 我改变了。关键是更改PROJECT urls.py,而不是APP urls.py 文件。

    例如,如果您的 PROJECT 名为“mysite”,而 APP 是“polls”,则您要更改的文件位于此处:

    /mysite/urls.py
    

    不是应用版本(位于 /polls/urls.py)。

    另外,您可能对我所做的错误感到生气,即将 /polls/urls.py 更改为新的“命名空间”语法,然后在对 /mysite/urls.py 进行更改后,忘记更改 / polls/urls.py 回到教程 3 的“编写更多视图”部分中给出的原始代码 (https://docs.djangoproject.com/en/1.7/intro/tutorial03/)

    希望这对某人有所帮助。 (这将是我第一次为 StackOverflow 做贡献!)

    【讨论】:

      【解决方案4】:

      我也完成了本教程,但在第 3 部分中遇到了一个问题,返回了相同的错误;我的困惑在于目录结构。

      我在我认为教程指定的目录中编写了 urls.py 文件,但它是~/mysite/urls.py,而教程实际上指定了~/mysite/mysite/urls.py

      教程还提示我们创建的文件~mysite/polls/urls.py 的位置正确,我应该怀疑两组指令只列出了内部目录(pollsmysite)。遇到此问题后,我不得不重新阅读教程的第 1 部分,但后来我终于从中理解了以下文字:

      内部的mysite/ 目录是您项目的实际 Python 包。

      【讨论】:

        【解决方案5】:

        您应该在“mysite/mysite/urls.py”文件中的 urlpatterns 类下尝试此语句“url(r'^polls/', include('polls.urls'))”,然后你可以看到你的内容渴望

        【讨论】:

          【解决方案6】:

          我有同样的问题,现在通过两种方式得到解决方案,通过编辑 [mysite/mysite/urls.py] 中的 urls.py 或更改 ROOT_URLCONF 如果您已经在 manage.py 所在的路径中编辑了 urls.py,请在 urls.py 的设置中。

          【讨论】:

            猜你喜欢
            • 2013-12-03
            • 2017-07-13
            • 2014-04-06
            • 2016-10-28
            • 1970-01-01
            • 2013-10-20
            • 2018-11-13
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多