我在这个论坛上阅读了很多答案,但它们并没有解决我的问题。我将非常感谢您的帮助。
我的文件views.py返回此错误:
from . import views
ImportError: cannot import name 'views' from '__main__' (C:/Users/tymot/Desktop/weather app/env/Environemnt/the_weather/weather/views.py)
views.py (Environemnt\the_weather\weather)
from django.shortcuts import render
from django.contrib import admin
def index(request):
return render(request, 'weather/index.html') #returns the index.html
urls.py (Environemnt\the_weather\weather)
from django.urls import path
from . import views
urlpatterns = [
path('', views.index), #the path for our index view
]
urls.py (Environemnt\the_weather\the_weather)
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('weather.urls')),
模板(the_weather\weather\templates\weather) 仅文件index.html
目录
-the_weather
--the_weather
---__init__
---setting
---urls
---wsgi
--weather
---migrations
----__init__
---templates
----weather
-----index
---__init__
---admin
---apps
---models
---tests
---urls
---views
--db
--manage.py
我尝试使用from __future__ importabsolute_import
或主页导入 View
来解决我的问题。我还尝试将views.py复制到目录模板(并修改其代码),但不幸的是它不起作用
最佳答案
您需要将您的 View
和url
分开,在您的应用程序中创建一个新模块(文件)urls.py
,在您的情况下是 weather
文件夹,并在其中添加这些代码,并将其从 views.py
中删除,您可以读取 here以便更好地理解它。
路径:the_weather/weather/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index), #the path for our index view
]
路径:the_weather/weather/views.py
from django.shortcuts import render
from django.contrib import admin
def index(request):
return render(request, 'weather/index.html') #returns the index.html template
关于python - 无法导入名称 'views' 、.Python、Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51327457/