【问题标题】:Is this a problem with the Django tutorial or a package problem, or is it me?这是Django教程的问题还是包的问题,​​还是我的问题?
【发布时间】:2010-09-03 21:49:58
【问题描述】:

我使用的是 Ubuntu 10,python 2.6.5

我正在关注本教程:http://www.djangobook.com/en/2.0/chapter02
我使用剪切和粘贴完成了所有步骤。 自动创建了以下目录结构:

bill@ed-desktop:~/projects$ ls -l mysite  
total 36  
-rw-r--r-- 1 bill bill     0 2010-09-01 08:18 __init__.py  
-rw-r--r-- 1 bill bill   546 2010-09-01 08:18 manage.py  
-rw-r--r-- 1 bill bill 20451 2010-09-01 18:50 mysite.wpr  
-rw-r--r-- 1 bill bill  3291 2010-09-01 08:18 settings.py  
-rw-r--r-- 1 bill bill   127 2010-09-01 11:13 urls.py  
-rw-r--r-- 1 bill bill    97 2010-09-01 08:20 views.py  

urls.py

from django.conf.urls.defaults import *
import sys
print sys.path

from mysite.views import hello
urlpatterns = patterns('',
    (r'^hello/$', hello),
)

pylint 产生这个错误:Unable to import 'mysite.views'

views.py

from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello world")


bill@ed-desktop:~/projects/mysite$ python manage.py runserver 

Validating models...
0 errors found

Django version 1.2.1, using settings 'mysite.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

导致:

Page not found (404)
Request Method:  GET
Request URL:  http://127.0.0.1:8000/

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
   1. ^hello/$ 
The current URL, , didn't match any of these. 

为什么主目录下的view.py会包含以下内容?

从 mysite.views 导入你好

没有子目录“views”。虽然我熟悉使用包,但我从来没有需要创建自己的包,所以我有点困惑。我会认为from views import hello 是正确的。

分步教程看起来很简单,我还没有看到其他人遇到过这个问题,所以我有点困惑我做错了什么。

【问题讨论】:

  • 可能完全不正确,但r'^hello/$' 应该是r'^/hello/$' 吗?
  • @dbr:不,语法是正确的。
  • 教程告诉你去http://127.0.0.1:8000/hello/
  • 是的,我在教程中错过了这个:127.0.0.1:8000/hello 和 (r'^$', hello),如果我只使用 127.0.0.1:8000 就可以了。谢谢

标签: python django packages


【解决方案1】:

您会看到 404 错误,因为您没有默认处理程序,请在 url 模式中添加如下内容:

('^$', views.default )

您可能需要将 Web 应用程序路径添加到 sys.path 变量才能“看到”您的模块:

import sys
sys.path.append(path_to_site)

【讨论】:

  • 当我添加 sys.path.append("..") mysite.view 导入错误消失了。再次感谢您。
【解决方案2】:

我不确定您的实际问题是什么。

您已经请求了根页面\,但只为\hello\ 定义了一个URL,所以显然Django 找不到您所请求的内容。如果您希望 hello 视图与站点根目录匹配,请执行以下操作:

urlpatterns = patterns('',
    (r'^$', hello),
)

我不明白关于from mysite.views import hello 的问题。如果 mysite 的父级在 Python 路径上,这将起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多