我是django的初学者,我在运行时遇到此错误:
python manage.py runserver
这是我的应用网址(main.urls)
from . import views
from main import views as main_views
from django.contrib.auth import views as auth_views
from main.views import blog, about
from django.conf.urls import include, url
urlpatterns = [
path('about/', 'main.views.about', name='about'),
path('', 'main.views.blog', name='blog'),
]
这是我的完整项目: https://github.com/ouakkaha/pr 如果您找到适合我的解决方案,我将非常感激:)
答案 0 :(得分:1)
您应通过删除引用以下内容的引号来实例化path
:
from main.views import blog, about
urlpatterns = [
path('about/', about, name='about'),
path('', blog, name='blog'),
]
由于您已经导入了视图,因此只应输入其名称。
the docs.中的更多信息
答案 1 :(得分:0)
我相信wencakisa的回答应该可以解决问题,但是让我从一开始就解释所有内容,也许会使情况变得更清楚。
在path
函数中,您需要传递三个参数:
在代码中,将 second 自变量放在引号path
中,这意味着它们只是字符串,而不是函数:
'main.views.about' # this is a string - just a few characters put together
main.views.about # this is a function, defined in the directory `main`,
# in the file `views`
另一个问题是进口。您的文件中有一些不必要的导入语句。如果要使用文件B中文件A中的对象(函数,类等),则必须将它们导入文件B中。您可以通过以下几种方式来实现它:
from . import views # reads: "from the same directory in which the current file (B) is,
# import `views.py`, and everything that's inside it."
# This is called "a relative import"
# and then you can use the imported objects like this:
path('about/', views.about, name='about')
from main import views as main_views # reads: "from the directory `main` in the project
# import the entire `views`, but call it `main_views`
# and then you can use the imported objects like this:
path('about/', main_views.about, name='about')
from main.views import blog, about # reads: from the `main/views.py` import only `blog`
# and `about` - these two are the functions you need
# and then you use them like this:
path('about/', about, name='about')
我建议您选择一种导入样式并始终使用它。在这种情况下,最后一个效果很好,因为您可以轻松查看已从views
文件导入了哪些功能。这样,其他两个import语句就是多余的,您可以将其删除。
希望这将帮助您解决问题。